C - does exec have to immediately follow fork in a multi-threaded process? C - does exec have to immediately follow fork in a multi-threaded process? multithreading multithreading

C - does exec have to immediately follow fork in a multi-threaded process?


Only the thread that calls fork will be running in the new process. However, there are limits to which functions you can call before exec. From fork:

A process shall be created with a single thread. If a multi-threaded process calls fork(), the new process shall contain a replica of the calling thread and its entire address space, possibly including the states of mutexes and other resources. Consequently, to avoid errors, the child process may only execute async-signal-safe operations until such time as one of the exec functions is called. Fork handlers may be established by means of the pthread_atfork() function in order to maintain application invariants across fork() calls.

I believe this means you should generally be okay, as long as any multi-threaded libraries use pthread_atfork properly.

EDIT: The pthread_atfork page explains further how the library can protect itself:

The expected usage is that the prepare handler acquires all mutex locks and the other two fork handlers release them.

For example, an application can supply a prepare routine that acquires the necessary mutexes the library maintains and supply child and parent routines that release those mutexes, thus ensuring that the child gets a consistent snapshot of the state of the library (and that no mutexes are left stranded). Alternatively, some libraries might be able to supply just a child routine that reinitializes the mutexes in the library and all associated states to some known value (for example, what it was when the image was originally executed).


As @Matthew wrote in his answer, the other threads from the parent process will not exist in the child process (if you are using PThreads).

Note that if this were not so, it wouldn't help to place the exec() call "immediately after" the call to fork, since there would still be the possibility that the other threads would run before the call to exec(). You could, however, control this by locking a mutex before calling fork() - it would essentially get destroyed by the call to exec().


I too thought , all the threads will be replicated in the child process too. But thats not true. Since other threads are not replicated in the child process, if you are using mutexes/locks before exec, you need to make sure that fork handlers are written to handle them properly.Here is an article on it.http://learnwithtechies.com/tech/index.php?option=com_content&view=article&id=15:fork-in-multithreaded-environment&catid=10:unix