36

If you are writing a multi-threaded application that uses system/library calls that make use of errno to indicate the error type, is there a safe way to use errno? If not, is there some other way to indicate the type of error that occurred rather than just that an error has occurred?

Erik Öjebo
  • 10,821
  • 4
  • 54
  • 75

2 Answers2

37

If your standard library is multithread aware, then it probably has a #define that changes errno into a function call that returns a thread-local error return value. However, to use this you generally must include <errno.h>, rather than relying on an extern declaration.

I found an article Thread-safety and POSIX.1 which addresses this very question.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • Thanks! A quick check in /usr/include/bits/errno.h confirmed that errno is indeed defined to be per-thread when using threads, on my Ubundu machine. – Erik Öjebo Jan 16 '09 at 08:04
19

man errno says:

errno is defined by the ISO C standard to be a modifiable lvalue of type int, and must not be explicitly declared; errno may be a macro. errno is thread-local; setting it in one thread does not affect its value in any other thread.

qrdl
  • 34,062
  • 14
  • 56
  • 86