How to set an environment variable when using system() to execute a command?

两盒软妹~` 提交于 2020-05-23 18:21:56

问题


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


回答1:


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
}

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.




回答2:


This should work:

#include "stdio.h"

int main()
{
    system("EXAMPLE=test env|grep EXAMPLE");
}

outputs

EXAMPLE=test




回答3:


Use setenv() api for setting environment variables in Linux

#include <stdlib.h>  
int setenv(const char *envname, const char *envval, int overwrite);

Refer to http://www.manpagez.com/man/3/setenv/ for more information.

After setting environment variables using setenv() use system() to execute any command.



来源:https://stackoverflow.com/questions/23128737/how-to-set-an-environment-variable-when-using-system-to-execute-a-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!