This may seem to be a dumb question but I don't really have a good understanding of fork()
other than knowing that this is about multi-threading. Child process is like a thread. If a task needs to be processed via fork()
, how to correctly assign tasks to parent process and child process?
-
1This question has been asked a million times. http://stackoverflow.com/questions/6210638/working-of-fork-in-c-language – Gillespie Feb 23 '15 at 18:24
-
2Also, forking is *not* about multi-threading, it's about creating new *processes*. – Gillespie Feb 23 '15 at 18:25
2 Answers
Check the return value of fork
. The child process will receive the value of 0
. The parent will receive the value of the process id of the child.

- 17,802
- 8
- 40
- 61
Read Advanced Linux Programming which has an entire chapter dedicated to processes (because fork
is difficult to explain);
then read documentation of fork(2); fork is not about multi-threading, but about creating processes. Threads are generally created with pthread_create(3) (which is implemented above clone(2), a Linux specific syscall). Read some pthreads tutorial to learn more about threads.
PS. fork
is difficult to understand (you'll need hours of reading, some experimentation, perhaps using strace(1), till you reach the "AhAh" insight moment when you have understood it) since it returns twice on success. You need to keep its result, and you need to test the result for the three cases : <0 (failure), ==0 (child), >0 (parent). Don't forget to later call waitpid(2) (or something similar) in the parent, to avoid having zombie processes.

- 223,805
- 18
- 296
- 547