c fork 的 child ppid 与 parent 的 pid 不匹配

c fork's child ppid does not match parent's pid

我对 C 完全陌生。 我尝试了以下代码,期望 child 的 ppid 与 parent 的 pid 匹配,但事实并非如此。

int main() {


    int pid;

    printf("I'm process with pid=%d\n", getpid());

    switch (pid = fork()) {
        case -1:
            perror("fork");
            exit(1);
        case 0:
            printf("I'm the child process: pid=%d, ppid=%d\n", getpid(), getppid());
            break;
        default:
            printf("I'm the parent process: pid=%d, ppid=%d\n", getpid(), getppid());
            break;
    }

    exit(0);

}
> gcc -o fork fork.c 
> ./fork 
I'm process with pid=16907
I'm the parent process: pid=16907, ppid=6604
I'm the child process: pid=16908, ppid=1 // <-- expected ppid=16907, why 1?
>

我做错了什么?

很可能父进程已经退出,不再存在。您可以尝试在父级中进行一些延迟。

'init' 这是 linux 系统中的根进程 运行 具有 pid 1 .

当进程的父进程在其自身(即子进程)之前终止时,子进程成为 'orphan' 进程并被根进程或进程占用就在创建它的进程的层次结构之上(父进程)。

因此,这里它被 pid = 1 的 init 占用并执行。 所以,延迟你的父进程来解决。

就像其他人提到的那样,看起来 parent 进程已终止,而 child 进程仍在执行中,使其(child 进程)成为 孤儿。在退出之前添加延迟可能会起作用。

但一种优雅的方式是,parent 进程必须等到 child 进程终止。

这可以通过使用 child 的 pid(fork() 返回的值)调用 waitpid() 来实现。当控件从这个函数中出来时,可以确定child进程已经终止。此外,waitpid() returns 进程终止的状态。根据它returns的状态,可以知道normal/abnormalchild终止。

这是执行此操作的代码:

int main() {


    int pid;
    int status = 0;

    printf("I'm process with pid=%d\n", getpid());

    switch (pid = fork()) {
        case -1:
            perror("fork");
            exit(1);
        case 0:
            printf("I'm the child process: pid=%d, ppid=%d\n", getpid(), getppid());
            break;
        default:
            waitpid(pid, &status, 0);
            if(WIFEXITED(status)
            {
                printf("Normal termination of child process %d\n", pid);
            }
            else
            {
                printf("Abormal termination of child process %d\n", pid);
            }
            printf("I'm the parent process: pid=%d, ppid=%d\n", getpid(), getppid());
            break;
    }

    exit(0);

}