问题
I have a C program that prints every environmental variable, whose name is given by stdin. It prints variables such as $PATH, $USER but it doesn't see the environmental variables i define myself in the Linux shell... For instance, in bash I define my=4, and I expect the program to return 4 when I give the input "my".
int main () {
char * key = (char * )malloc(30);
scanf("%s", key);
if(getenv(key) != NULL)
printf("%s\n", getenv(key));
else
printf("NULL\n");
return 0;
}
What can I do in order to improve the results of getenv? I want it to show me all the environmental variables with all the inheritances from the Linux shell . Thank you..
回答1:
There are a couple of ways:
my=4; export my; ./program
my=4 ./program
env my=4 ./program
Each of these methods has the same effect, but through different mechanisms.
This method is specific to the shell that you're using, although it works like this in most typical shells (Bourne shell variants; csh-derived shells are different again). This first sets a shell variable, then exports it to an environment variable, then runs your program. On some shells, you can abbreviate this as
export my=4
. The variable remains set after your program runs.This method is also dependent on your shell. This sets the
my
environment variable temporarily for this execution of./program
. After running,my
does not exist (or has its original value).This uses the
env
program to set the environment variable before running your program. This method is not dependent on any particular shell, and is the most portable. Like method 2, this sets the environment variable temporarily. In fact, the shell never even knew thatmy
was set.
回答2:
If you didn't export
it then it's just a shell variable, not an environment variable. Use export my=4
or my=4; export my
.
回答3:
This has nothing to do with C or getenv
. If you do my=4
in the shell, you have defined a local shell variable. To make that an environment variable, do export my
.
来源:https://stackoverflow.com/questions/5402355/using-getenv-function