Re: Ayuda con funcion en C

From: Alvaro Herrera <alvherre(at)alvh(dot)no-ip(dot)org>
To: Edwin Quijada <listas_quijada(at)hotmail(dot)com>
Cc: pgsql-es-ayuda(at)postgresql(dot)org
Subject: Re: Ayuda con funcion en C
Date: 2009-08-28 16:56:50
Message-ID: 20090828165650.GH7070@alvh.no-ip.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-es-ayuda

Edwin Quijada escribió:

> Datum
> pg_serverid(PG_FUNCTION_ARGS)
> {
> int32 arg = PG_GETARG_INT32(0);
> char *cmd = "php /proc/lotod/movil/serverkey.php";
> char *arch = "/proc/lotod/movil/serverkey.php";
> char buf[BUFSIZ];
> FILE *fp,*ptr;
>
> text *new_t = (text *) palloc(LENMAX);
>
>
> if ((fp = fopen(arch,"r"))==NULL) {PG_RETURN_BOOL(false);}
>
> if ((ptr = popen(cmd, "r")) != NULL)
> while (fgets(buf, BUFSIZ, ptr) != NULL);
> (void) pclose(ptr);
>
> memcpy(VARDATA(new_t),buf,strlen(buf)); // <==esta es lo que copia a la variable
> PG_RETURN_TEXT_P(new_t);
> }

1. Si popen falla, buf[] puede tener cualquier basura. Necesitas
manejar ese caso.

2. el while(); es confuso. Evitalo. De hecho estás confundido de cómo
funciona, como lo demuestra la indentación errónea de tu programa. La
indentación correcta es así:

if ((ptr = popen(cmd, "r")) != NULL)
while (fgets(buf, BUFSIZ, ptr) != NULL)
;
(void) pclose(ptr);

lo cual es malo, por ejemplo porque invocas pclose() incluso cuando
popen falla.

3. Creo que tu función debería ser más o menos así:

if ((ptr = popen(cmd, "r")) != NULL) {
int ret;
while (fgets(buf, BUFSIZ, ptr) != NULL)
;
ret = pclose(ptr);
if (ret == -1)
ereport(ERROR,
(errmsg("pclose falló: %m")))
len = strlen(buf);
new_t = palloc(len + VARHDRSZ);
memcpy(VARDATA(new_t), buf, len);
SET_VARSIZE(new_t, len + VARHDRSZ);
PG_RETURN_TEXT_P(new_t);
}

PG_RETURN_NULL();

en realidad el while(fgets) no me gusta mucho porque tampoco chequea
errores, y no verifiqué que la sintaxis de las macros es la correcta.

--
Alvaro Herrera http://www.flickr.com/photos/alvherre/
"When the proper man does nothing (wu-wei),
his thought is felt ten thousand miles." (Lao Tse)

In response to

Browse pgsql-es-ayuda by date

  From Date Subject
Next Message Rafael Martinez 2009-08-28 17:10:27 Re: Ayuda con funcion en C
Previous Message Edwin Quijada 2009-08-28 16:49:12 RE: Ayuda con funcion en C