tags:

views:

272

answers:

1

I have the method below, and it correctly sets the ret value to 0 (indicating success in setenv), but when I check to see if this environment variable is actually set, it's absent. Why would this be happening?

 void Class::mysetenv(char* a, char* b)                           
     {   
         if(a==0 || b==0)
             return;

         int ret = setenv(strdup(a), strdup(b), 1);
         printf("ret: %d %s %s\n", ret, a, b);                          
     }
+11  A: 

Your function leaks. The manpage of setenv says:

This function makes copies of the strings pointed to by name and value

So you don't have to copy them yourself before passing them to it.

Do you execute your program like this from within the shell?

./a.out FOO 42

Well, then the environment variable will be set for the process so executed (a.out), and be inherited to the processes launched by it. But it will not "bubble up" into the shell that executed a.out. That is also the reason why commands such as set or export are shell built-ins rather than real programs. Checkout "help export" in bash.

Johannes Schaub - litb
I'm calling this function inside of a program from a child thread. Since you mentioned bubbling up, would this mean the change only occurs for the child thread and not for the parent thread?
samoz
if you mean from a forked process, yes it would only affect the process in which you executed the setenv. the parent process won't be affected. execute setenv before the fork instead.
Johannes Schaub - litb
those are not called "threads" but "processes". a thread is just another execution path within the same process. but your ones are separate processes same mistake here: http://stackoverflow.com/questions/658431/after-execvp-returns-why-doesnt-my-program-pick-up-where-it-left-off
Johannes Schaub - litb
That was it! Thank you!
samoz