【发布时间】:2017-09-22 16:00:43
【问题描述】:
这是测试 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返回:0时,是在子进程中。但是子进程显示 我是 pid 为 25111 的孩子。我以为子进程pid应该是0,为什么会变成25111呢?
和父进程一样,fork返回25111,但是getpid()返回25110(我是pid为25110的父进程,等待子进程)
【问题讨论】:
-
您需要阅读更多内容。阅读advancedlinuxprogramming.com;我们无法在这里解释什么需要整本书来解释。请注意,
fork是难以理解的,所以花点时间!还要多次阅读 fork(2) 和 fork wikipage -
顺便说一句,唯一的PID是0是
init -
init是 pid 1。从字面上看(这是 POSIX 要求)没有 pid 0 这样的东西,因为 0 对于接受或返回 pid 的各种接口具有特殊含义——尤其是 @ 987654329@. -
@R.. 我也是这么想的,尽管在我尝试过的第一台机器(一台旧的 SunOS 机器)上,
ps显示了一个名为“swapper”的 pid 0。 (但是,是的,init 是 pid 1。) -
@SteveSummit:它是内核进程管理中的一个伪进程,但你不能使用任何带有 pid 参数的函数与它交互,因为它不是有效的 pid 号。我认为 Linux 同样有一个“pid 0”,它是空闲任务(无论如何对于 cpu0)。