在waitpid之前让子进程不僵尸

时间:2017-03-13 13:52:04

标签: linux unix process waitpid

是否有Linux或POSIX方法用于指示进程在完成且父进程未调用waitpid()时变为僵尸?

我知道父进程我们可以使用SA_NOCLDSTOP来处理SIGCHLD处理程序,但在我的情况下这不是一个选项,因为父进程繁忙且SIGCHLD正在用于其他的东西。

如果我对退出代码不感兴趣,有没有办法将特定的子进程标记为自己悄然死亡?

1 个答案:

答案 0 :(得分:0)

您将始终需要等待子进程,但是如果您按照此过程进行操作,那么您可以等待一个快速死亡的孩子,并让init继承您的真实'处理。然后,Init会为你整理。

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

void main(void) {
    int ret;
    pid_t child1;
    pid_t child2;
    int status;

    child1 = fork();
    if (child1 == -1) {
        /* error */
        exit(1);
    }

    if (child1 == 0) {
        /* in the child... we create a new session, and then re-fork */
        setsid();

        child2 = fork();
        if (child2 == -1) {
            exit(1);
        }

        if (child2 == 0) {
            /* call execve() or a friend */
            ret = execlp("sleep", "sleep", "6", NULL);

            /* we should _never_ get here - unless the execlp() fails */
            fprintf(stderr, "execlp() returned: %d\n", ret);
            exit(1);
            for(;;);
        }

        sleep(2); 

        /* success ... child1 dies here */
        exit(0);
    }

    sleep(4);

    ret = waitpid(child1, &status, 0);
    if (ret != 0) {
        /* unfortunately we can only determine the state of our 'proxy' process...
         * to get any further information / the child-child PID, then you'll need to use a pipe to share the information */
        fprintf(stderr, "waitpid() returned %d\n", ret);
    }

    sleep(4); 

    return;
}

各种睡眠持续时间应允许您查看以下事件(观看top或其他内容)。

第1步

所有进程都会启动,所有进程都作为shell的子进程链接

  • 17336 - 我的外壳
  • 21855 - 申请
  • 21856 - Child1(代理程序)
  • 21857 - Child2(有用的子进程)

top输出:

attie    17336 17335  0 16:04 pts/36   00:00:00 -bash
attie    21855 17336  0 16:34 pts/36   00:00:00 ./test
attie    21856 21855  0 16:34 ?        00:00:00 ./test
attie    21857 21856  0 16:34 ?        00:00:00 sleep 6

第2步

Child1 死亡,变成僵尸/不存在, Child2 被init(PID 1)继承

attie    17336 17335  0 16:04 pts/36   00:00:00 -bash
attie    21855 17336  0 16:34 pts/36   00:00:00 ./test
attie    21856 21855  0 16:34 ?        00:00:00 [test] <defunct>
attie    21857     1  0 16:34 ?        00:00:00 sleep 6

第3步

Child1 在调用waidpid()

时被父母清除
attie    17336 17335  0 16:04 pts/36   00:00:00 -bash
attie    21855 17336  0 16:34 pts/36   00:00:00 ./test
attie    21857     1  0 16:34 ?        00:00:00 sleep 6

第4步

Child2 死亡,并被init清除

attie    17336 17335  0 16:04 pts/36   00:00:00 -bash
attie    21855 17336  0 16:34 pts/36   00:00:00 ./test