Why does fork sometimes return parent and sometimes child?

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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:

  • the future parent process calls fork();
  • the kernel creates a new process, which is the child, and sets various things up appropriately — but both processes are running the same code and are “waiting” for a return from the same function;
  • both processes continue running (not necessarily straight away, and not necessarily simultaneously, but that’s besides the point):
    • 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.

Method 2

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x