Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

getenv can easily be misused in a single threaded program.


But it is possible to safely use it in a single threaded program.

There's no way to use it safely in a multi threaded application that may use setenv (unless you add your own synchronisation, and ensure everything uses it, even third party libraries).


Actually I don't believe that's the case. The getenv function as described by ISO C cannot be safely used in a program that only uses getenv, if that program uses ISO C threads, and more than one threat calls getenv without synchronizing with the others.

I don't think POSIX fixes this: it doesn't specify that the environ array is protected against concurrent access.

If two threads call getenv right around the same time, one of them could invalidate the environ array just as the other one has started to traverse it.

If you want to be safe, copy the environment to a different data structure on program startup. Then have all your threads refer to that data structure.


Hmm, I'm apparently correct for C++11, where calling getenv only is thread safe, but that's not guaranteed by earlier standards (or, as far as I can tell, by C or POSIX).


I'm surprised C++ would have anything to say about getenv; mostly it just includes the standard C library via normative reference.



Interesting. So in a multi-threaded C++ program that only calls the std:: getenv function, everything is fine.

If anything calls the C getenv function, like a third party library, things are maybe not fine.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: