[linxu]SUBREAPER 设置祖父进程接管孙子进程

Posted adream307

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[linxu]SUBREAPER 设置祖父进程接管孙子进程相关的知识,希望对你有一定的参考价值。

测试代码

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

int main()
    pid_t pid = fork();
    if(pid<0) return -2;
    if(pid==0) //child
        printf("child, pid = %d, ppid = %d\\n",getpid(),getppid());
        pid = fork();
        if(pid<0) return -3;
        if(pid==0) //grandchild
            sleep(1);
            printf("grandchild, pid = %d, ppid=%d\\n",getpid(),getppid());
        else
            exit(0);
        
        exit(0);
    else//parent
        printf("parent, pid = %d\\n",getpid());
        sleep(2);
    
    printf("exit from parent\\n");
    return 0;

上述测试程序中,grandchild 是从 child 那里 fork 出来的,正常情况下,当child 退出后,grandchild 的父进程为pid1init,这样parent进程就无法收接收来自grandchildSIGCHLD信号,程序运行结果如下:

parent, pid = 30809
child, pid = 30810, ppid = 30809
grandchild, pid = 30811, ppid=1
exit from parent

设置 SUBREAPER 标记,代码如下:

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

int main()
    int ret = prctl (PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0);
    if(ret<0) return -1;
    pid_t pid = fork();
    if(pid<0) return -2;
    if(pid==0) //child
        printf("child, pid = %d, ppid = %d\\n",getpid(),getppid());
        pid = fork();
        if(pid<0) return -3;
        if(pid==0) //grandchild
            printf("before child exit, grandchild, pid = %d, ppid = %d\\n",getpid(),getppid());
            sleep(2);
            printf("after child exit, grandchild, pid = %d, ppid = %d\\n",getpid(),getppid());
        else
            sleep(1);
            exit(0);
        
        exit(0);
    else//parent
        printf("parent, pid = %d\\n",getpid());
        sleep(3);
    
    printf("exit from parent\\n");
    return 0;

程序输出如下:

parent, pid = 32232
child, pid = 32233, ppid = 32232
before child exit, grandchild, pid = 32234, ppid = 32233
after child exit, grandchild, pid = 32234, ppid = 32232
exit from parent

当前 child 退出后,grandchildparent 接管

以上是关于[linxu]SUBREAPER 设置祖父进程接管孙子进程的主要内容,如果未能解决你的问题,请参考以下文章

linxu学习之进程

linxu下查看进程的线程方法

Linxu:进程的管理与进程的延迟性&周期性调度

LINXU多线程(进程与线程区别,互斥同步)

每天一个linxu命令6之jps ?查看java进程的端口

linxu-nginx重启