这是测试fork()系统调用的C代码:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<wait.h>
int main(int argc, char *argv[])
{
printf("I am: %d\n", (int)getpid());
pid_t pid = fork();
printf("fork returned: %d\n", (int)pid);
if (pid < 0)
{
perror("fork failed");
}
if (pid==0)
{
printf("I am the child with pid %d\n", (int)getpid());
sleep(5);
printf("Child exiting...\n");
exit(0);
}
printf("I am the parent with pid %d, waiting for the child\n", (int)getpid());
wait(NULL);
printf("Parent ending. \n");
return 0;
}
终端输出是:
I am: 25110
fork returned: 25111
I am the parent with pid 25110, waiting for the child
fork returned: 0
I am the child with pid 25111
Child exiting...
Parent ending.
问题:当 fork returned: 0 时,它处于子进程中 . 但是子进程显示 I am the child with pid 25111 . 我以为子进程pid应为0,为什么它变为25111?
与父流程 fork returned 25111 相同,但getpid()返回25110(我是pid 25110的父亲,等待孩子)
2 回答
不 . 在父母
fork()
中返回孩子的pid . 在孩子中,fork
返回0 - 这不是任何东西的pid,它只是一个标记 . 孩子的pid是25111,正如getpid
告诉你的那样 .对 . 父母的pid总是25110,正如
getpid
告诉你的那样 . 并且fork()
返回了新孩子的pid .fork
在父级中返回的值与getpid
中返回的相同值证明了这一切都正常 .听起来你觉得
fork()
总是返回你有意义的过程的pid - 我们已经有了getpid
的调用 .如果您是父级,
fork()
将返回另一个进程的pid,即子级 . 如果你是孩子,那么你想知道你父母的pid,这是一个好的,频繁的,独立的问题 . 答:致电getppid()
. )我们可以总结如下:
记住这一点的方法是考虑将要调用的代码
fork()
:它将要做什么,需要知道什么 . 父母需要知道它是父母 . 孩子需要知道这是孩子 . 父母经常需要知道孩子的pid(并且没有其他方法可以获得它) .如果
fork
总是返回一个pid,那么在fork
调用之后,查看它的返回值,你将无法知道你是父母还是孩子 - 但这通常是你需要知道的第一个也是最重要的事情 .(在所有这些中,我忽略了第三种可能性,即
fork
失败,并在父级中返回-1,并且没有't return anything in the child, because there isn't . )另见Why fork() return 0 in the child process? .
fork
返回0并不意味着你的pid是0.这只是返回值fork
用来告诉你你是孩子的过程 . 事实上fork
永远不会回报你的pid;它会返回:你孩子的pid,
0,意思是你是孩子,或者
-1,表示发生了错误(并且未创建子进程)