Search code examples
clinuxoperating-systempthreadsfork

What happens when a thread forks?


I know calling fork() sys_call from a thread is a bad idea. However, what will happen if a thread creates a new process using fork()?

The new process will be the child of the main thread that created the thread. I think.

If its parent finishes first, the new process will be attached to init process. And its parent is main thread, not the thread that created it.

Correct me if I am wrong.

#include <stdio.h>
#include <pthread.h>

int main () 
{
     thread_t pid;
     pthread_create(&(pid), NULL, &(f),NULL);
     pthread_join(tid, NULL);
     return 0;
}

void* f()
{
     int i;
     i = fork();

     if (i < 0) {
         // handle error
     } else if (i == 0) // son process
     {
          // Do something;
     } else {
          // Do something;
     }
 }

Solution

  • The new process will be the child of the main thread that created the thread. I think.

    fork creates a new process. The parent of a process is another process, not a thread. So the parent of the new process is the old process.

    Note that the child process will only have one thread because fork only duplicates the (stack for the) thread that calls fork. (This is not entirely true: the entire memory is duplicated, but the child process will only have one active thread.)

    If its parent finishes first, the new process will be attached to init process.

    If the parent finishes first a SIGHUP signal is sent to the child. If the child does not exit as a result of the SIGHUP it will get init as its new parent. See also the man pages for nohup and signal(7) for a bit more information on SIGHUP.

    And its parent is main thread, not the thread that created it.

    The parent of a process is a process, not a specific thread, so it is not meaningful to say that the main or child thread is the parent. The entire process is the parent.

    One final note: Mixing threads and fork must be done with care. Some of the pitfalls are discussed here.