Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are threads copied when calling fork?

People also ask

Are threads copied in fork?

A fork() duplicates all the threads of a process.

Does fork duplicate only the calling thread?

The POSIX fork() or Solaris fork1() duplicates only the thread that calls it. (Calling the Solaris fork() duplicates all threads, so this issue does not come up.)

What happens when you call fork in a thread?

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 .

Is forking the same as threading?

Threading runs multiple lines of execution intra-process. Forking is a means of creating new processes.


No.

Threads are not copied on fork(). POSIX specification says (emphasize is mine):

fork - create a new process

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.

To circumvent this problem, there exists a pthread_atfork() function to help.


man fork:

The child process is created with a single thread—the one that called fork(). The entire virtual address space of the parent is replicated in the child, including the states of mutexes, condition variables, and other pthreads objects; the use of pthread_atfork(3) may be helpful for dealing with problems that this can cause.


From The Open Group Base Specifications Issue 7, 2018 edition's fork:

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.

When the application calls fork() from a signal handler and any of the fork handlers registered by pthread_atfork() calls a function that is not async-signal-safe, the behavior is undefined.