getenv() fails
Giorgos Keramidas
keramida at ceid.upatras.gr
Mon Jul 12 23:43:53 PDT 2004
On 2004-07-13 01:33, Miguel Cardenas <mfcardenas at 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 at orion:~$ env | grep HOSTNAME
: keramida at 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 at orion:~$ gcc -O -Wall -o lala lala.c
: keramida at orion:~$ ./lala
: getenv error
: keramida at orion:~$ env HOSTNAME="testhost" ./lala
: HOSTNAME=testhost
: keramida at 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
More information about the freebsd-questions
mailing list