23

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?

ks1322
  • 31,484
  • 13
  • 100
  • 154
MetallicPriest
  • 27,365
  • 43
  • 180
  • 324
  • Have you seen [this question](http://stackoverflow.com/questions/1235516/fork-in-multi-threaded-program)? Or [this one](http://stackoverflow.com/questions/1073954/fork-and-existing-threads)? Basically only the `fork()`ing thread survives in the child process. What are you trying to achieve? – Zecc May 19 '11 at 10:17
  • Actually I was trying to create a replicated process for reliable execution, where the replicated process would verify the outputs from primary process by executing the same code. – MetallicPriest May 23 '11 at 13:20

3 Answers3

24

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

Community
  • 1
  • 1
DarkDust
  • 87,789
  • 19
  • 183
  • 216
18

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.

Mat
  • 195,986
  • 40
  • 382
  • 396
0

No.

A fork creates a new process with his own thread(s), copies the file descriptor and the virtual memory.

A child process does NOT share the same memory with his father. So this is absolutely not the same.

Intrepidd
  • 18,310
  • 5
  • 54
  • 63