Why isn't my wrapper around setenv() working?
Asked Answered
B

1

3

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);                          
     }
Bozcaada answered 19/3, 2009 at 14:42 Comment(0)
D
13

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.

Delisle answered 19/3, 2009 at 14:47 Comment(3)
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?Bozcaada
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.Delisle
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: #658931Delisle

© 2022 - 2024 — McMap. All rights reserved.