Why fork() return 0 in the child process?

16,973

Solution 1

As to the question you ask in the title, you need a value that will be considered success and cannot be a real PID. The 0 return value is a standard return value for a system call to indicate success. So it is provided to the child process so that it knows that it has successfully forked from the parent. The parent process receives either the PID of the child, or -1 if the child did not fork successfully.

Any process can discover its own PID by calling getpid().

As to your update question, it seems a little backward. Any process can discover its parent process by using the getppid() system call. If a process did not track the return value of fork(), there is no straight forward way to discover all the PIDs of its children.

Solution 2

You need to return something that cannot be a real PID (otherwise the child may think it is the parent).

0 fits the bill.

Solution 3

From the docs:

RETURN VALUES

Upon successful completion, fork() returns a value of 0 to the child process and returns the process ID of the child process to the parent process. Otherwise, a value of -1 is returned to the parent process, no child process is created, and the global variable errno is set to indi- cate the error.

Share:
16,973
zangw
Author by

zangw

Nobody is a worse programmer than your past self.

Updated on July 24, 2022

Comments

  • zangw
    zangw almost 2 years

    As we know, the fork() will return twice, namely two PIDs. The PID of the child process is returned in the parent, and 0 is returned in the child.

    Why the 0 is returned in the child process? any special reason for that?

    UPDATE I was told that the linked list is used between parent and child process, and parent process knows the PID of child process, but if there is no grandchildren, so the child process will get 0. I do not know whether it is right?