You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C程序子进程打印错误父ID:为何父ID始终为707而非pid1?

子进程父ID显示为707而非原父进程PID的原因

你的问题核心是原父进程在子进程完成输出前就已经退出,导致子进程成为孤儿进程,被系统的初始化进程(PID为707,通常是systemd或其他init替代进程)收养,因此getppid()返回的是这个收养进程的ID,而非原父进程的PID(6560)。

问题代码

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main() {
    pid_t pid1 = getpid();
    printf("the parent id is %d \n", pid1);

    if (pid1 % 2 != 0) {
        printf("the parent id is odd\n");

    } else {
        printf("%d\n", getpid());
        printf("its even two childs were created\n");
        int i = fork();

        if (i == 0) {
            printf("child 1 chiled id is %d, parent is %d\n", getpid(),
                   getppid());

        } else {
            int i2 = fork();
            if (i2 == 0) {
                printf("child 2 chiled id is %d, parent is %d\n", getpid(),
                       getppid());
            }
        }
    }
}

运行输出

the parent id is 6560 
6560
its even two childs were created
child 2 chiled id is 6562, parent is 707
child 1 chiled id is 6561, parent is 707

原因分析

调用fork()创建子进程后,原父进程没有等待子进程执行完成就直接退出。此时子进程还在运行(进程调度时机导致父进程先于子进程退出),这些子进程会被系统的初始化进程接管——这是Linux系统处理孤儿进程的机制,避免出现无父进程的进程(僵尸进程的前置情况)。

解决办法

在父进程中添加wait()或waitpid()调用,让父进程等待所有子进程执行完毕后再退出。修改后的代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main() {
    pid_t pid1 = getpid();
    printf("the parent id is %d \n", pid1);

    if (pid1 % 2 != 0) {
        printf("the parent id is odd\n");

    } else {
        printf("%d\n", getpid());
        printf("its even two childs were created\n");
        int i = fork();

        if (i == 0) {
            printf("child 1 chiled id is %d, parent is %d\n", getpid(),
                   getppid());
            exit(0); // 子进程执行完毕后退出
        } else {
            int i2 = fork();
            if (i2 == 0) {
                printf("child 2 chiled id is %d, parent is %d\n", getpid(),
                       getppid());
                exit(0); // 子进程执行完毕后退出
            } else {
                // 父进程等待两个子进程结束
                wait(NULL);
                wait(NULL);
            }
        }
    }
    return 0;
}

修改后预期输出

the parent id is 6560 
6560
its even two childs were created
child 1 chiled id is 6561, parent is 6560
child 2 chiled id is 6562, parent is 6560

修改后,父进程会等待两个子进程都执行完毕才退出,子进程的父ID就会始终是原父进程的PID(6560),不会再被707号进程收养。

内容的提问来源于stack exchange,提问作者Rama Zain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 21:10:03