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

六眼飞鱼酱① 提交于 2019-12-10 20:14:54

问题


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);                          
     }

回答1:


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.



来源:https://stackoverflow.com/questions/662466/why-isnt-my-wrapper-around-setenv-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!