在C设置环境变量

在C设置环境变量

问题描述:

反正是有使用C设置在Linux环境变量?我试过SETENV()和putenv()函数,但他们似乎并没有为我工作。

Is there anyway to set environment variables in linux using C? I tried setenv() and putenv(), but they don't seem to be working for me.

先谢谢了。

我要作胡乱猜测这里,但正常的原因,这些功能似乎不工作是不是因为他们不工作,而是因为用户并不真正了解环境变量是如何工作的。举例来说,如果我有这样的程序:

I'm going to make a wild guess here, but the normal reason that these functions appear to not work is not because they don't work, but because the user doesn't really understand how environment variables work. For example, if I have this program:

int main(int argc, char **argv)
{
  putenv("SomeVariable=SomeValue");
  return 0;
}

然后我从shell中运行它,它不会修改shell环境 - 有没有办法一个子进程来做到这一点。这就是为什么修改环境的shell命令是内建命令,以及为什么你需要包含您要添加到您的外壳,而不是简单地运行它的变量设置的脚本

And then I run it from the shell, it won't modify the shell's environment - there's no way for a child process to do that. That's why the shell commands that modify the environment are builtins, and why you need to source a script that contains variable settings you want to add to your shell, rather than simply running it.