【问题标题】:Parent pid_t of a child process created after fork()在 fork() 之后创建的子进程的父 pid_t
【发布时间】:2014-03-12 18:21:05
【问题描述】:

我有以下功能:

void test_fork()
{
    pid_t id;

    printf("Parent process id: %d\n", getpid());

    id = fork();

    if (id == 0)
        printf("\nChild:");
    else if (id > 0)
        printf("\nParent:");
    else
        exit(EXIT_FAILURE);

    printf("\nprocess id: %d\n", getpid());
    printf("parent process id: %d\n", getppid());
}

我的怀疑与它的输出有关,特别是有时我有例如以下简单的输出:

Parent process id: 879

Parent:
process id: 879
parent process id: 878

Child:
process id: 881
parent process id: 879

最后一个 id 等于其父 id (正如预期的那样)。

但有时输出例如:

Parent process id: 858

Parent:
process id: 858
parent process id: 857

Child:
process id: 860
parent process id: 1

最后一个id不等于它的父进程id,但等于1(应该是init进程的id)。

这怎么可能?

【问题讨论】:

    标签: c unix process pid


    【解决方案1】:

    这是因为当子进程请求其父进程的pid时父进程已经完成,所以子进程的父进程默认为init进程。 init 进程的pid1

    尝试将wait() 放在父进程中!!

    【讨论】:

      【解决方案2】:

      这是因为父进程在子进程运行之前就退出了,而让子进程成为第一个进程的子进程。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-28
        • 2011-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多