Reputation: 109
I had a doubt on using fork on a multi-threaded process. If a process has multiple threads (already created using pthread_create and did a pthread_join) and I call fork, will it copy the same functions assigned to the threads in the child process or create a space where we can reassign the functions?
Upvotes: 3
Views: 3341
Reputation: 754900
Read carefully what POSIX says about fork()
and threads. In particular:
- 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.
The child process will have a single thread running in the context of the calling thread. Other parts of the original process may be tied up by threads that no longer exist (so mutexes may be locked, for example).
The rationale section (further down the linked page) says:
There are two reasons why POSIX programmers call
fork()
. One reason is to create a new thread of control within the same program (which was originally only possible in POSIX by creating a new process); the other is to create a new process running a different program. In the latter case, the call tofork()
is soon followed by a call to one of theexec
functions.The general problem with making
fork()
work in a multi-threaded world is what to do with all of the threads. There are two alternatives. One is to copy all of the threads into the new process. This causes the programmer or implementation to deal with threads that are suspended on system calls or that might be about to execute system calls that should not be executed in the new process. The other alternative is to copy only the thread that callsfork()
. This creates the difficulty that the state of process-local resources is usually held in process memory. If a thread that is not callingfork()
holds a resource, that resource is never released in the child process because the thread whose job it is to release the resource does not exist in the child process.When a programmer is writing a multi-threaded program, the first described use of
fork()
, creating new threads in the same program, is provided by thepthread_create()
function. Thefork()
function is thus used only to run new programs, and the effects of calling functions that require certain resources between the call tofork()
and the call to an exec function are undefined.
Upvotes: 8