Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying environment variable within a C program

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;
}
like image 720
jruiz Avatar asked Apr 10 '26 09:04

jruiz


2 Answers

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
The setenv() function adds the variable name to the environment with the value value, if name does not already exist. If name does exist in the environment, then its value is changed to value if overwrite is nonzero; if overwrite is zero, then the value of name is not changed. This function makes copies of the strings pointed to by name and value (by contrast with putenv(3)).

like image 37
suspectus Avatar answered Apr 13 '26 00:04

suspectus