Situation:
I have a multithreaded program written in C. If one of the threads forks, the child process is replaced by another using exec() and the parent waits for the child to exit.
Problem:
After the child process is created by fork() there are a few lines of code that compile the arguments to be used in the following exec() command.
Hypothesis
Am I correct in assuming that in the time between the child process being created by fork() and being replaced by exec(), the child process – being a copy of the parent – will have all the threads of the parent and therefore these threads will run – albeit for a very brief period?
If so, is the correct solution to call exec() immediately after fork()?
Only the thread that calls
forkwill be running in the new process. However, there are limits to which functions you can call beforeexec. Fromfork:I believe this means you should generally be okay, as long as any multi-threaded
libraries use
pthread_atforkproperly.EDIT: The
pthread_atforkpage explains further how the library can protect itself: