17

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 ?

2 Answers 2

24

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 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.

The POSIX 2018 specification of fork() is similar.

1
  • 1
    Thanks. The link is of great help.
    – Mac13
    Commented Jul 2, 2009 at 23:39
0

Threads are not inherited from a child process on a linux system using fork(). An in-depth source is here: http://linas.org/linux/threads-faq.html

1
  • 3
    That FAQ is very out of date. The largest user-visible difference is that LinuxThreads has been obsoleted by NPTL ever since kernel 2.6 and glibc 2.3, which resolves all outstanding issues with non-POSIX-like threading behavior.
    – ephemient
    Commented Jul 2, 2009 at 18:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.