On a linux system, does the child process view the existing threads the same way as the parent process ?
int main() {
//create thread 1
int child_pid = fork();
if ( 0 == child_pid)
{
..
}
else
{
..
}
Since the whole address space is copied for the child process, what happens to the state of the threads. What if the thread 1 in the above segment is waiting on a conditional signal. Is it in the waiting state in child process as well ?
A fork() duplicates all the threads of a process. The problem with this is that fork() in a process where threads work with external resources may corrupt those resources (e.g., writing duplicate records to a file) because neither thread may know that the fork() has occurred.
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.
Threading runs multiple lines of execution intra-process. Forking is a means of creating new processes.
Because threads are not inherited across fork, issues arise. At the time of the call to fork , threads in the parent process other than the one calling fork may have been executing critical regions of code. As a result, the child process may get a copy of objects that are not in a well-defined state.
Threads on Linux nowadays try to stay POSIX compliant. Only the calling thread is replicated, not other threads (note that e.g. on Solaris you can choose what fork does depending on what library you link to)
From http://www.opengroup.org/onlinepubs/000095399/functions/fork.html (POSIX 2004):
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 theexec
functions is called. Fork handlers may be established by means of thepthread_atfork()
function in order to maintain application invariants acrossfork()
calls.
The POSIX 2018 specification of fork()
is similar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With