从ac程序执行"echo $ PATH"?

AJ.*_*AJ. 1 c linux path exec

我试图从C程序显示,设置和修改PATH环境变量.我这样做: -

char *cmd[] = { "echo", "$PATH", (char *)0 };
if (execlp("echo", *cmd) == -1)
Run Code Online (Sandbox Code Playgroud)

但我没有得到结果.

unw*_*ind 6

你应该使用getenv(),没有必要通过shell:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
   printf("PATH='%s'\n", getenv("PATH"));

   return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

但你不会能够改变的价值.环境变量继承到子进程,但子进程有自己的副本.无论使用哪种语言编写,都无法从其他程序更改shell的环境.您当然可以更改自己的流程价值,但这不是您要求的.

在shell本身中,您可以更改其当前环境设置,但仅限于此处.这就是您需要使用"source"来运行更改环境的shell脚本的原因.