here\'s a weird thing I found today on Mac OSX.
After a fork, which has succeeded, errno is set at 0 in the father\'s process (as expected), but set at 22 in the chi
Curious...I can reproduce the problem on Mac OS X 10.9 Mavericks with GCC 4.8.2 and with Clang.
POSIX says that some functions that fail will set errno
(and fork() is one of those functions), but does not say that functions that succeed will not set errno
. For example, on Solaris, many standard I/O functions set errno
if the output stream is not a terminal. However, resetting errno = 0;
after the printf()
doesn't alter the behaviour on Mac OS X.
Some functions provide the error number in a variable accessed through the symbol
errno
, defined by including the<errno.h>
header. The value oferrno
should only be examined when it is indicated to be valid by a function's return value. No function in this volume of POSIX.1-2008 shall seterrno
to zero. For each thread of a process, the value oferrno
shall not be affected by function calls or assignments toerrno
by other threads.
If fork()
failed, then errno
would be set to indicate the failure. When it succeeds, it is not technically valid to inspect errno
. And this is a demonstration of why.
POSIX says:
Upon successful completion, fork() shall return 0 to the child process and shall return the process ID of the child process to the parent process. Both processes shall continue to execute from the fork() function. Otherwise, -1 shall be returned to the parent process, no child process shall be created, and errno shall be set to indicate the error.
which means errno
is specified to be set on success only. Otherwise nothing is specified, so you can expect an old value of errno
or any unspecified value.