When running the fork
call to create a new process, if it succeed it returns either 0
(the child) or the parent.
I didn't get the idea behind this. Why doesn't fork
just always return child
or always parent
?
When you fork()
, the code that’s running finds itself running in two processes (assuming the fork is successful): one process is the parent, the other the child. fork()
returns 0 in the child process, and the child pid in the parent process: it’s entirely deterministic.
This is how you can determine, after the fork()
, whether you’re running in the parent or the child. (And also how the parent knows the child pid — it needs to wait on it at some point.)
In a little more detail:
fork()
;fork()
returns 0 to the child process, which continues and uses that information to determine that it’s the child;fork()
returns the child pid to the parent process, which continues and uses that information to determine that it’s the parent.fork is executed by the parent process. so I thought we still the parent process and we always get
pid` of the child. I dont get the idea of how the current process running fork can become the child process (case it returns 0)
Commented
Apr 27, 2017 at 16:01
fork()
starts a new process, but it doesn’t tell the kernel “here, start a new process and run this piece of code in it” — both the current and the new process continue running the same code.
Commented
Apr 27, 2017 at 16:05
The fork()
system call "returns twice", always (unless it fails). In the parent, it returns the PID of the child process, and in the child, it returns zero.
The usual flow is
pid_t pid;
int status;
pid = fork();
if (pid == 0) {
run_child_stuff();
exit(0);
} else if (pid > 0) {
run_parent_stuff();
wait(&status); /* wait for child to exit */
} else {
/* handle failure to fork */
}
... or similar.
fork
does?