Changing a environmental variable through a C program

 ̄綄美尐妖づ 提交于 2019-12-11 08:15:51

问题


Anyone knows how can I change the Linux environmental variables through a C program? I dont want to change the environmental variables that are copied for the execution of that program. I want to be able to change its value from a C program and then when executing the command 'env' in linux I can see its value changed.

Any tips?


回答1:


I dont want to change the environmental variables that are copied for the execution of that program. I want to be able to change its value from a C program and then when executing the command 'env' in linux I can see its value changed

You can't. You can only change the environment of your own process. You have no way of ever touching the environment of the parent. Put another way, anything you do (setting / clearing environment variables, changing local directory, etc.) will be invisible for the parent process.

The standard clearly states:

The setenv() function shall update or add a variable in the environment of the calling process.

The only way to change the environment of the parent is to get it to do it himself.




回答2:


See POSIX functions setenv and putenv.

setenv http://pubs.opengroup.org/onlinepubs/009604599/functions/setenv.html

putenv http://pubs.opengroup.org/onlinepubs/009604599/functions/putenv.html

As POSIX says The setenv() function is preferred over this function. (putenv)

I dont want to change the environmental variables that are copied for the execution of that program.

As @cnicutar put in his answer you can only change the environment variable for your current process and not for its parent process or another process.



来源:https://stackoverflow.com/questions/11710029/changing-a-environmental-variable-through-a-c-program

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