Reputation: 11
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?
Upvotes: 1
Views: 3930
Reputation: 145829
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.
Upvotes: 2
Reputation: 182639
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.
Upvotes: 3