使用system()执行命令时如何设置环境变量? [英] How to set an environment variable when using system() to execute a command?
问题描述
我正在Linux上编写C程序,需要使用system()
执行命令,并且在执行该命令时需要设置环境变量,但是我不知道在使用<时如何设置env var. c0>.
I'm writing a C program on Linux and need to execute a command with system()
, and need to set an environment variable when executing that command, but I don't know how to set the env var when using system()
.
推荐答案
如果要将环境变量传递给与父进程不同的子进程,则可以组合使用 setenv
.假设您要将另一个PATH
传递给您的孩子:
If you want to pass an environment variable to your child process that is different from the parent, you can use a combination of getenv
and setenv
. Say, you want to pass a different PATH
to your child:
#include <stdlib.h>
#include <string.h>
int main() {
char *oldenv = strdup(getenv("PATH")); // Make a copy of your PATH
setenv("PATH", "hello", 1); // Overwrite it
system("echo $PATH"); // Outputs "hello"
setenv("PATH", oldenv, 1); // Restore old PATH
free(oldenv); // Don't forget to free!
system("echo $PATH"); // Outputs your actual PATH
}
否则,如果您只是创建一个新的环境变量,则可以使用 setenv
和 unsetenv
,如下所示:
Otherwise, if you're just creating a new environment variable, you can use a combination of setenv
and unsetenv
, like this:
int main() {
setenv("SOMEVAR", "hello", 1); // Create environment variable
system("echo $SOMEVAR"); // Outputs "hello"
unsetenv("SOMEVAR"); // Clear that variable (optional)
}
当然不要忘了检查错误代码.
And don't forget to check for error codes, of course.
这篇关于使用system()执行命令时如何设置环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!