Which child process will inherit threads of parent process

multithreadingoperating systems

What happens when one process has child threads and a child process, will child process inherit all child threads of parent process?

Assume OS is Linux. Let it be Java Threading model.

Best Answer

The short answer is that the child process inherits one thread from the parent, namely the thread that had called fork.

This is from the Posix/Pthreads point of view. Linux usually tries to stay close to Posix so this also mostly applies to Linux, although Linux may have some features outside of Posix that behave differently.

One might ask why just one thread is inherited instead of all. Apparently an alternative call forkall was considered and rejected for Posix. At first glance this seems like it might be useful. Actually, though, it's easy to see how it could lead to intractable bugs. Consider a case where thread A has opened a file and is about to issue a write to it. At that precise moment, thread B calls forkall. Since thread A is duplicated in the child process, and (in general) all open files are duplicated in the child process, thread A and its clone in the child both write to the open file. This is most likely an error.

Even having the child process inherit just a single thread is problematic. See this stackoverflow question and a good blog article that it links to. The upshot is that there are issues but they can be dealt with.

The Solaris Threads model, which predates Pthreads, had a different policy regarding fork and threads. By default the fork system call cloned all threads whereas the fork1 system call cloned just the calling thread. Worse, when Pthreads was implemented in Solaris, the way the program was linked defined whether it was using Solaris threads or Pthreads semantics, which determined the semantics of fork. Very confusing.

Finally, you had asked about Java threads. The way a new process is forked in Java is using the java.lang.Runtime.exec() method. This fuses the functions of Posix fork and exec. In general, the subprocess need not be running a Java Virtual Machine (JVM), so none of the Java threads from the parent exist in the child. Even if the child does end up running a JVM, that JVM starts fresh by running the main() method of the start-class, and it doesn't inherit any threads from the parent.

Related Topic