Is "getenv" thread safe?

Is “getenv” thread safe under QNX? Under the POSIX rules
it should be. See IEEE Std 1003.1c-1995 Interpretation #39 at
http://standards.ieee.org/reading/ieee/interp/1003-1c-95_int/pasc-1003.1c-39.html

But the QNX helpfile suggests that it might not be.

It should at least be thread safe against other “getenv”
calls, even if there’s a problem with calls that change
the environment.

John Nagle
Team Overbot

John Nagle <nagle@overbot.com> wrote:

Is “getenv” thread safe under QNX? Under the POSIX rules
it should be. See IEEE Std 1003.1c-1995 Interpretation #39 at
http://standards.ieee.org/reading/ieee/interp/1003-1c-95_int/pasc-1003.1c-39.html

Not according to the current POSIX standard:

http://www.opengroup.org/onlinepubs/007904975/functions/getenv.html

It should at least be thread safe against other “getenv”
calls, even if there’s a problem with calls that change
the environment.

Actually, since the specs have always said that the string may be
overwritten by a subsequent call to getenv(), setenv(), or unsetenv()
(without restricting it to subsequent calls in the same thread),
requiring the function to be thread-safe is less useful than it seems.

Thread-safe only means that the function does what the specs say it
does, even if another thread calls a thread-unsafe function. Even if
getenv() is thread-safe, you still need to make sure that other threads
can’t call it until after you’re done looking at the returned string.
Making getenv() thread-unsafe only adds the requirement that you must
also make sure that other threads can’t call any other thread-unsafe
function while you’re calling getenv().

Wojtek Lerch <wojtek_l@yahoo.ca> wrote:

Actually, since the specs have always said that the string may be
overwritten by a subsequent call to getenv(), setenv(), or unsetenv()
(without restricting it to subsequent calls in the same thread),
requiring the function to be thread-safe is less useful than it seems.

Thread-safe only means that the function does what the specs say it
does, even if another thread calls a thread-unsafe function. Even if

Um… Sorry, I was thinking about signal-safe… The definition of
thread-safe is different (and somewhat more vague):

Thread-safe

A function that may be safely invoked concurrently by multiple
threads.

Still, if two threads calling getenv() can overwrite each other’s
strings, the promise that it’s “safe” to do that doesn’t really buy you
much. The only case I can of where the change in POSIX.2001 breaks
valid code in when multiple threads call getenv(), but only to see if it
returns NULL or not, without looking at the string.