为什么fork()在子进程中返回0? [英] Why fork() return 0 in the child process?

查看:575
本文介绍了为什么fork()在子进程中返回0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道,fork()将返回两次,即两个PID.子进程的PID会在父级中返回,而0会在子级中返回.

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.

为什么在子进程中返回0?有什么特殊原因吗?

更新有人告诉我,父进程和子进程之间使用了链表,并且父进程知道子进程的PID,但是如果没有孙子进程,则子进程将获得0我不知道这是对的吗?

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?

推荐答案

对于标题中提出的问题,您需要一个将被视为成功且不能为实际PID的值. 0返回值是用于指示成功的系统调用的标准返回值.因此,将其提供给子进程,以便它知道它已成功从父进程派生.父进程接收子进程的PID,如果子进程未成功分叉,则返回-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.

任何进程都可以通过调用getpid()来发现自己的PID.

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

关于您的更新问题,似乎有些落后.任何进程都可以使用getppid()系统调用来发现其父进程.如果某个进程没有跟踪fork()的返回值,则没有直接的方法来发现其子级的所有PID.

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.

这篇关于为什么fork()在子进程中返回0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆