Link to home
Start Free TrialLog in
Avatar of Risky101
Risky101Flag for United States of America

asked on

How do I set a Linux environment variable from within C/C++

Hi,

I wish to set a Linux environment variable from within GNU C/C++.

I've tried "system("var=hello"); but this doesnt work - the variable seems to disappear when I check it in a shell script.
Avatar of sunnycoder
sunnycoder
Flag of India image

man setenv

       #include <stdlib.h>

       int setenv(const char *name, const char *value, int overwrite);
the variable seems to disappear when I check it in a shell script
you cannot set an variable from within your program which is still alive after this program exits
The only way to do this is to exit your program with any of the exec*() function, calling another program or shell
i would agree with ahoffmann,  env variables can be passed on to children processes, but not escalated up to parents., hence in the C program, whatever u set , will die once the program dies.. unless u exec some shell/program from there in.
Avatar of Risky101

ASKER

the program 'read' (built into Bash) manages to set the environment variable properly, ie:

read yesno
if [ "$yesno" = "y" ];then
  # do something
fi

So far, I've tried:
system("yesno=\"n\");
setenv()
system ("export etc etc");
system ("declare etc etc");

Without exception, the variables disappear when the program exits. Is there any way, any at all, to set an environment variable, just like read does?

>  the program 'read' (built into Bash) manages to set the environment variable properly, ie:
NO.

> Without exception, the variables disappear when the program exits.
yes, as already said.
ASKER CERTIFIED SOLUTION
Avatar of jmcg
jmcg
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial