Question

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);                          
     }
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top