2

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

4

3 回答 3

6

有几种方法:

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

这些方法中的每一种都具有相同的效果,但通过不同的机制。

  1. 此方法特定于您正在使用的 shell,尽管它在大多数典型的 shell 中都是这样工作的(Bourne shell 变体;csh 派生的 shell 再次不同)。这首先设置一个shell 变量,然后将其导出到一个环境变量,然后运行您的程序。在某些 shell 上,您可以将其缩写为export my=4. 程序运行后变量保持设置。

  2. 此方法还取决于您的 shell。这将临时my设置环境变量以执行. 运行后,不存在(或有其原始值)。./programmy

  3. 这使用env程序在运行程序之前设置环境变量。此方法依赖于任何特定的 shell,并且是最便携的。与方法 2 一样,这会临时设置环境变量。事实上,shell 甚至都不知道它my被设置了。

于 2011-03-23T08:09:30.110 回答
4

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.

于 2011-03-23T08:08:03.953 回答
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.

于 2011-03-23T08:08:22.433 回答