6 ms·
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 y
by davidt84 2y ago
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).
- kazinator 2y agoActually 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.
- davidt84 2y agoHmm, 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).
- kazinator 2y agoI'm surprised C++ would have anything to say about getenv; mostly it just includes the standard C library via normative reference.
- davidt84 2y agoNevertheless, https://en.cppreference.com/w/cpp/utility/program/getenv https://en.cppreference.com/w/cpp/utility/program/getenv
- kazinator 2y agoInteresting. 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.