Using getenv function

…衆ロ難τιáo~ 提交于 2019-12-11 03:59:49

问题


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:

  1. my=4; export my; ./program
  2. my=4 ./program
  3. env my=4 ./program

Each of these methods has the same effect, but through different mechanisms.

  1. 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.

  2. 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).

  3. 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 that my 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!