Risky101
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.
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.
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
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.
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?
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.
NO.
> Without exception, the variables disappear when the program exits.
yes, as already said.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
#include <stdlib.h>
int setenv(const char *name, const char *value, int overwrite);