简体   繁体   English

从交流程序执行“ echo $ PATH”?

[英]Executing “echo $PATH” from a c program?

I am trying to display, set & modify PATH environment variable from a C program. 我正在尝试从C程序显示,设置和修改PATH环境变量。 I am doing something like this:- 我正在做这样的事情:

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

But I am not getting the results. 但是我没有得到结果。

You should use getenv () , there's no need to go through a shell: 您应该使用getenv () ,无需遍历shell:

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

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

   return EXIT_SUCCESS;
}

But you won't be able to change the value. 但是您将无法 更改该值。 Environment variables are inherited into child processes, but the child has its own copy. 环境变量被继承到子进程中,但是子进程拥有自己的副本。 You can't change the shell's environment from a different program, regardless in which language it's written. 不管使用哪种语言编写,都无法从其他程序更改外壳的环境。 You can of course change your own process' value, but that's not what you asked to do. 您当然可以更改自己的流程的价值,但这不是您要执行的。

In the shell itself, you can change its current environment settings, but only there. 在外壳程序本身中,您可以更改其当前环境设置,但只能在此更改。 This is why you need to use "source" to run shells scripts that change the environment. 这就是为什么您需要使用“源代码”来运行更改环境的Shell脚本的原因。

If you want to display $PATH , try this: 如果要显示$PATH ,请尝试以下操作:

#include <stdlib.h>

printf("PATH: %s\n",getenv("PATH"));

if you want to modify it, use setenv() or putenv() . 如果要修改它,请使用setenv()putenv()

try this: 尝试这个:

char *cmd[] = { "$PATH", (char *)0 };
if (execlp("echo", cmd) == -1)
#include <stdio.h>
#include <stdlib.h>

...

char *pPath;
pPath = getenv("PATH");
if (pPath!=NULL)
    printf ("The current path is: %s",pPath);
putenv("PATH=somepath");

...

Better solutions already given, but by way of explanation; 已经给出了更好的解决方案,但只是作为解释; the $PATH variable is parsed and translated by the command shell, not the echo command itself. $ PATH变量是由命令外壳(而不是echo命令本身)解析和转换的。 The solutions already suggested use getenv() to obtain the environment variable's value instead. 已经建议的解决方案使用getenv()代替来获取环境变量的值。

To invoke the command shell to perform this: 要调用命令shell来执行此操作:

system( "echo $PATH" ) ;

but that solution is somewhat heavyweight since it invokes a new process and the entire command processor just to do that. 但是该解决方案在某种程度上是重量级的,因为它调用了一个新进程,而整个命令处理器只是这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM