0

Can we update the run-time value using system() in c?

int abcd()
{
   int temp1=0;

   char *env=NULL;
   env=getenv("ENVIRONMENT");
   sscanf(env,"%d",&temp1);
   temp1=temp1+1;
   printf("%d",temp1);
   sprintf(env,"%d",temp1);
   setenv("ENVIRONMENT",env,0);
} 

I want to use system() instead of setenv.

Initially before running the code I have given in linux shell export ENVIRONMENT=0.

tohuwawohu
  • 13,268
  • 4
  • 42
  • 61
  • Why you want to use system() instead of setenv() – Chinna Jan 08 '14 at 10:58
  • This sounds weird, since it is not such a good idea to use `system` at all, since at least one additional process will be spawned! – urzeit Jan 08 '14 at 11:00
  • setenv is not working correctly i want to set the enviroment value using system() – user3158318 Jan 08 '14 at 11:01
  • 1
    The problem is that if you change the environment via system, it will only get changed in the scope of the command processor spawned by `system`. Are you aware of that no process can change it's parents process environment? – urzeit Jan 08 '14 at 11:04
  • so what can be the possible solution actually after my system resets i want the incremented value of ENVIRONMENT in my system. But its getting lost – user3158318 Jan 08 '14 at 11:08
  • The only method I'm aware of is to output the variable to stdout or stderr and then set the environment within the shell you want it to be changed in (by `.`ing a shell script, e.g.). – urzeit Jan 08 '14 at 11:12
  • See http://stackoverflow.com/questions/17929414/how-to-use-setenv-to-export-a-variable-in-c (the section introduced by "NOTE") – urzeit Jan 08 '14 at 11:14

1 Answers1

3

No you cannot.

system() is forking off a new process which then has its own environment. All changes it makes to it will not effect the environment of the parent process, so you won't notice any effect of a setenv it might do (unless the child process does additional things after the setenv). When the child process terminates (probably very quickly), then that changed environment is forgotten.

You are stuck with the proper setenv call. Maybe you should ask a new question concerning your problems with that one.

To change the parent process's environment, the parent process has to change it. The child can only give information back to its parent which then will have to use this information. A typical way of doing such a thing is this:

Parent process (e. g. in a shell):

eval "$(child)"

Child process (e. g. in C):

printf("setenv ENVIRONMENT=%d\n", value+1);
Alfe
  • 56,346
  • 20
  • 107
  • 159