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?
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 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 offork()
, there is no straight forward way to discover all the PIDs of its children.From the docs:
You need to return something that cannot be a real PID (otherwise the child may think it is the parent).
0
fits the bill.From the book(Advanced Programing in the unix)