On success, the PID of the child process is returned in the parent’s thread of execution, and a 0 is returned in the child’s thread of execution.
p = fork();
I'm confused at its manual page,is p
equal to 0
or PID
?
On success, the PID of the child process is returned in the parent’s thread of execution, and a 0 is returned in the child’s thread of execution.
p = fork();
I'm confused at its manual page,is p
equal to 0
or PID
?
Once
fork
is executed, you have two processes. The call returns different values to each process.If you do something like this
You will see both the messages printed. They're being printed by two separate processes. This is they way you can differentiate between the two processes created.
Processes are structured in a directed tree where you only know your single-parent (
getppid()
). In short,fork()
returns-1
on error like many other system functions, non-zero value is useful for initiator of the fork call (the parent) to know its new-child pid.Nothing is as good as example:
And the result (bash is pid 2249, in this case):
If you need to share some resources (files, parent pid, etc.) between parent and child, look at
clone()
(for GNU C library, and maybe others)I think that it works like this: when pid = fork(), the code should be executed two times, one is in current process, one is in child process. So it explains why if/else both execute. And the order is, first current process, and then execute the child.
This is the cool part. It's equal to BOTH.
Well, not really. But once
fork
returns, you now have two copies of your program running! Two processes. You can sort of think of them as alternate universes. In one, the return value is0
. In the other, it's theID
of the new process!Usually you will have something like this:
In this case, both strings will get printed, but by different processes!
I'm not sure how the manual can be any clearer!
fork()
creates a new process, so you now have two identical processes. To distinguish between them, the return value offork()
differs. In the original process, you get the PID of the child process. In the child process, you get 0.So a canonical use is as follows:
fork()
is invoked in the parent process. Then a child process is spawned. By the time the child process spawns,fork()
has finished its execution.At this point,
fork()
is ready to return, but it returns a different value depending on whether it's in the parent or child. In the child process, it returns 0, and in the parent process/thread, it returns the child's process ID.