使用 getenv 函数
我有一个 C 程序,可以打印每个环境变量,其名称由 stdin 给出。 它打印 $PATH、$USER 等变量,但看不到我在 Linux shell 中自己定义的环境变量... 例如,在 bash 中我定义了 my=4,并且当我输入“my”时,我希望程序返回 4。
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 的所有继承。 谢谢..
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..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有几种方法:
my=4;导出我的; ./program
my=4 ./program
env my=4 ./program
这些方法中的每一个都具有相同的效果,但通过不同的机制。
此方法特定于您正在使用的 shell,尽管它在大多数典型 shell 中的工作方式如下(Bourne shell 变体;csh 派生的 shell 又有所不同)。首先设置一个shell 变量,然后将其导出到环境变量,然后运行您的程序。在某些 shell 上,您可以将其缩写为
export my=4
。该变量在程序运行后保持设置状态。此方法还取决于您的 shell。这将为
./program
的执行临时设置my
环境变量。运行后,my
不存在(或具有其原始值)。这使用
env
程序在运行程序之前设置环境变量。此方法不依赖于任何特定的 shell,并且是最可移植的。与方法 2 类似,这会临时设置环境变量。事实上,shell 甚至不知道my
已设置。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.如果您没有
导出
它,那么它只是一个 shell 变量,而不是环境变量。使用export my=4
或my=4;导出我的
.If you didn't
export
it then it's just a shell variable, not an environment variable. Useexport my=4
ormy=4; export my
.这与 C 或 getenv 无关。如果您在 shell 中执行
my=4
,则您已经定义了本地 shell 变量。要使其成为环境变量,请执行export my
。This has nothing to do with C or
getenv
. If you domy=4
in the shell, you have defined a local shell variable. To make that an environment variable, doexport my
.