Date: Tue, 13 Jul 2004 09:46:04 +0300 From: Giorgos Keramidas <keramida@ceid.upatras.gr> To: Miguel Cardenas <mfcardenas@prodigy.net.mx> Cc: freebsd-questions@freebsd.org Subject: Re: getenv() fails Message-ID: <20040713064604.GB39956@orion.daedalusnetworks.priv> In-Reply-To: <200407130133.41534.mfcardenas@prodigy.net.mx> References: <200407130133.41534.mfcardenas@prodigy.net.mx>
next in thread | previous in thread | raw e-mail | index | archive | help
On 2004-07-13 01:33, Miguel Cardenas <mfcardenas@prodigy.net.mx> wrote: > Hello... > > I have a problem getting the hostname from the HOSTNAME var... > > #include <stdlib.h> > ... > char* host = getenv("HOSTNAME"); > > returns always NULL... why? if I do 'echo $HOSTNAME' it is visible, > but inside my C program returns NULL... what is wrong? is it a bug? No, it's not a bug. I don't think there's something wrong either. What you see is most likely a result of the fact that HOSTNAME is not an 'environment variable' of your shell but just a plain shell variable. The following small program that uses getenv() can be used to test this. The commands provided by your shell can be used too. See below: 1 #include <stdio.h> 2 #include <stdlib.h> 3 4 int 5 main(void) 6 { 7 char *s; 8 9 s = getenv("HOSTNAME"); 10 if (s == NULL) { 11 fprintf(stderr, "getenv error\n"); 12 exit(EXIT_FAILURE); 13 } 14 printf("HOSTNAME=%s\n", s); 15 return EXIT_SUCCESS; 16 } By running 'env' you can see what variables are exported to the child processes of your shell. : keramida@orion:~$ env | grep HOSTNAME : keramida@orion:~$ echo $HOSTNAME : orion.daedalusnetworks.priv Clearly HOSTNAME isn't one of them. Using the program shown above and env(1) you can verify this: : keramida@orion:~$ gcc -O -Wall -o lala lala.c : keramida@orion:~$ ./lala : getenv error : keramida@orion:~$ env HOSTNAME="testhost" ./lala : HOSTNAME=testhost : keramida@orion:~$ Obiously, HOSTNAME is set in the parent shell, but not exported to `lala' when it runs. Explicitly setting it with env(1) works as expected though. Giorgos
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20040713064604.GB39956>