Is it possible to modify an environment variable within a C program. Something like this:
#include <stdlib.h>
int main( void )
{
system( "echo $VARIABLE" );
system( "VARIABLE=somethig");
system( "echo $VARIABLE" );
return 0;
}
Use setenv() or
putenv(). Beware the gotchas with putenv().
Your code as written sets the environment of a new shell interpreter spawned by call to system(). That environment is discarded when system() returns.
setenv(const char *name, const char *value, int overwrite); is the function you need.
e.g. setenv("CONFIG_PATH", "/etc", 0);
From the man page:
DESCRIPTION
Thesetenv()function adds the variablenameto the environment with the valuevalue, ifnamedoes not already exist. Ifnamedoes exist in the environment, then its value is changed tovalueif overwrite is nonzero; if overwrite is zero, then thevalueofnameis not changed. This function makes copies of the strings pointed to bynameandvalue(by contrast withputenv(3)).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With