使用getenv的功能 [英] Using getenv function

查看:271
本文介绍了使用getenv的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有打印每一个环境变量,其名称由标准输入给出一个C程序。
它打印变量,如$ PATH,$ USER但没有看到环境变量定义我自己在Linux shell中...
例如,在bash我定义我= 4,我希望该计划返回4当我给输入我的。

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;
}

我可以为了提高getenv的结果做什么?
我希望它给我看所有的环境变量从Linux shell中的所有遗产。
谢谢。

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. 我= 4;导出我的; ./program

  2. 我= 4 ./program

  3. env中我= 4 ./program

  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. 这方法是特定于您正在使用的外壳,但它的工作原理是这样的最典型的壳(Bourne shell的变种; CSH衍生弹是不同的再次)。这首先设置一个的 shell变量的,然后将它导出到的环境变量的,然后运行程序。在一些贝壳,可以缩写本作导出我= 4 。该变量保持你的程序运行后设置。

  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.

这方法也依赖于你的shell。这台我的环境变量的暂时的这个执行 ./程序的。运行后,我的不存在(或有其原始值)。

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

本使用 ENV 程序运行程序之前设置环境变量。这种方法是<青霉>不的依赖于任何特定的外壳,并且是最便携的。类似的方法2,本次临时设置环境变量。事实上,外壳甚至从未知道我的设置。

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.

这篇关于使用getenv的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆