Take the 2-minute tour ×

In C++ using pthreads, what happens to your other threads if one of your threads calls fork?

It appears that the threads do not follow. In my case, I am trying to create a daemon and I use fork() with the parent exiting to deamonize it. However, in a new path through the code, I create some threads before the fork and some after. Is there an easy way to change ownership of the threads over to the new forked process rather than moving all my thread creation after the fork?

share|improve this question
add comment

4 Answers

up vote 7 down vote accepted

Nothing. Only the thread calling fork() gets duplicate. The child process has to start any new threads. The parents threads are left alone.

share|improve this answer
What happens to the threads when the parent of the fork exit()s? –  WilliamKF Apr 9 '12 at 22:53
@WilliamKF stackoverflow.com/questions/395877/… –  Andrew Finnell Apr 10 '12 at 0:29
add comment

It's usually very bad to fork a thread. The forked process is supposed to be a complete copy of the parent, except with threads it isn't. There is a function pthread_atfork() which helps sometimes. If you must fork a thread, it is best if you call exec() immediately after the fork().

I suggest you read the caveats from the POSIX developers in the documentation of fork() and pthread_atfork() (See http://pubs.opengroup.org/onlinepubs/007904975/functions/fork.html and http://pubs.opengroup.org/onlinepubs/007904975/functions/pthread_atfork.html ).

From the fork() documentation:


share|improve this answer
add comment

Nothing, unless one happens to be preempted by the thread running the new process.

share|improve this answer
add comment

In POSIX when a multithreaded process forks, the child process looks exactly like a copy of the parent, but in which all the threads stopped dead in their tracks and disappeared.

This is very bad if the threads are holding locks.

For this reason, there is a crude mechanism called pthread_atfork in which you can register handlers for this situation.

Any properly written program module (and especially reusable middleware) which uses mutexes must call pthread_atfork to register some handlers, so that it does not misbehave if the process happens to call fork.

Besides mutex locks, threads could have other resources, such as thread-specific data squirreled away with pthread_setspecific which is only accessible to the thread (and the thread is responsible for cleaning it up via a destructor).

In the child process, no such destructor runs. The address space is copied, but the thread and its thread specific value is not there, so the memory is leaked in the child. This can and should be handled with pthread_atfork handlers also.

share|improve this answer
add comment

Your Answer


