Can fork() function be used to replicate a multithreaded process. And if so, will all threads be exactly the same and if not, why not. If replication can't be done through fork, is there any other function which can do it for me?
The fork( ) system call creates an exact duplicate of the address space from which it is called, resulting in two address spaces executing the same code. Problems can occur if the forking address space has multiple threads executing at the time of the fork( ).
Multi-threading is both challenging and rewarding. Show activity on this post. Threads are functions run in parallel, fork is a new process with parents inheritance. Threads are good to execute a task in parallel, while forks are independent process, that also are running simultaneously.
Threading runs multiple lines of execution intra-process. Forking is a means of creating new processes.
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.
After a fork, only one thread is running in the child. This is a POSIX standard requirement. See the top answer to the question fork and existing threads ?.
No, the child will only have one thread. Forking a threaded process is not trivial. (See this article Threads and fork(): think twice before mixing them for a good rundown).
I don't know of any way of cloning a process and all its threads, I don't think that's possible on Linux.
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