Why fork() return 0 in the child process?

2019-05-27 08:56发布

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?

4条回答
劫难
2楼-- · 2019-05-27 09:44

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 of fork(), there is no straight forward way to discover all the PIDs of its children.

查看更多
叛逆
3楼-- · 2019-05-27 09:51

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.

查看更多
狗以群分
4楼-- · 2019-05-27 09:54

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

0 fits the bill.

查看更多
啃猪蹄的小仙女
5楼-- · 2019-05-27 09:58

From the book(Advanced Programing in the unix)

The reason fork returns 0 to the child is that a process can have only a single parent, and the child can always call getppid to obtain the process ID of its parent. (Process ID 0 is reserved for use by the kernel, so it’s not possible for 0 to be the process ID of a child.)

查看更多
登录 后发表回答