Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why fork() return 0 in the child process?

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?

like image 498
zangw Avatar asked Sep 08 '14 06:09

zangw


People also ask

What is the return value for the fork () in a child process?

RETURN VALUE Upon successful completion, fork() returns 0 to the child process and returns the process ID of the child process to the parent process. Otherwise, -1 is returned to the parent process, no child process is created, and errno is set to indicate the error.

What does it mean when fork returns zero value?

Fork creates a duplicate process and a new process context. When it returns a 0 value it means that a child process is running, but when it returns another value that means a parent process is running.

What happens when you fork a child process?

When a process calls fork, it is deemed the parent process and the newly created process is its child. After the fork, both processes not only run the same program, but they resume execution as though both had called the system call.

Does fork return child PID?

If you're the parent, fork() returns the pid of the other process, the child. And if you're the child, fork() doesn't return a pid at all. (If you're the child and you want to know the pid of your parent, that's a good, frequent, and separate question.


Video Answer


1 Answers

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.

like image 130
jxh Avatar answered Oct 09 '22 07:10

jxh