Why fork(2) doesn’t copy all threads?

There are many advises discouraging the use of fork in threaded applications…it is even on “Programming with POSIX Threads” by Butenhof….Avoid using fork in threaded program (if you can) unless you intend to exec a new program immediately.

Certainly using fork in threaded programs is not a good idea but sometimes it becomes necessary, so, the point is: why fork(2) doesn’t copy all threads?

First time I  asked myself  “does a forked process have all the parent’s threads?” I thought yes but, I was wrong.  The specification say it: A process shall be created with a single thread

So why?

  • Because is more practical, easier, and less complex.
    • There are only two alternatives, copy all of them or copy just the one calling fork. Each alternative has it own set of complexities, so, which approach is easier to follow? Copying only the thread that called fork.
  • Critical sections: Other threads could be executing critical sections at fork() call, therefore child process might get a copy of objects that are in undefined status => causing undefined behavior on the application. Σ =
  • Parent and child could be reading from fd or socket at the same time, or even worse writing to it.  あぶない
  • Since state in parent and child should be the same, all parent’s threads should be stopped before to be forked and if in the middle of a system call EINTR would be raised
  • .

Specification mentions forkall was rejected, that means that I was not alone.
It is easier to deal with one thread using pthread_atfork() than dealing with multiple threads on the child.
As long as it is specified it is OK