Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Note that this code first sets errno to 0 to comply with ERR30-C. Set errno to zero before calling a library function known to set errno, and check errno only after the function returns a value indicating failure.

Noncompliant Code Example (C99, strerror_

...

r()

...

)

This noncompliant code example uses the POSIX strerror_r() function, which has the same functionality as strerror() but guarantees thread safety.

...

While this code prevents a race window from being exploited within the strerror_r() function itself, the fact that errno is a static variable means there is still a race window between the fopen() call and the beginning of the strerror_r() call, in which another thread could modify errno.

Compliant Solution (

...

C99 mutex) 

This compliant solution adds a mutex to protect the access of errno by multiple threads.

...

Note that Linux provides two versions of strerror_r(), known as the XSI-compliant version and the GNU-specific version. This compliant solution assumes the XSI-compliant version. You can get the XSI-compliant version if you compile applications in the way POSIX requires (that is, by defining _POSIX_C_SOURCE or _XOPEN_SOURCE appropriately). Check your strerror_r() manual page to see which version(s) are available on your system.

...

Compliant Solution (C11 strerror_s()

...

This compliant solution uses the strerror_s() function from Annex K of the C Standard, which has the same functionality as strerror() but guarantees thread-safety. Furthermore, in C11, errno is a thread-local variable, so there is no race condition between when it is initialized and read by strerror_s().

...