zoukankan      html  css  js  c++  java
  • (转载)Linux使用prctl API, 在父进程退出后,让子进程也退出

    (转载)http://www.cnblogs.com/cornsea/archive/2010/06/08/1754369.html

    例子1:

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <signal.h>
    #include <sys/prctl.h>
    
    void my_system(void)
    {
        pid_t pid;
        pid = fork();
        if (pid == 0)
        {
            //prctl(PR_SET_PDEATHSIG, SIGHUP);
            while (1)
            {
                printf("child running...\n");
                sleep(1);
            }
            exit(0);
        }
        else if (pid < 0)
        {
            printf("create failed\n");
        }
    }
    
    int main (int argc, char *argv[])
    {
        int i = 0;
        my_system();
    
        while (i++ < 6)
        {
            printf("father running...\n");
            sleep(1);
        }
    
        printf("Main exit()\n");
    
        return 0;
    }

    程序输出:

    [root@localhost ~]# ./a.out
    child running...
    father running...
    child running...
    father running...
    child running...
    father running...
    child running...
    father running...
    child running...
    father running...
    child running...
    father running...
    child running...
    Main exit()
    [root@localhost ~]# child running...
    child running...
    child running...
    child running...
    child running...
    child running...

    可以看到当父进程结束了,子进程还在运行,此时的子进程变成了孤儿进程了。

    例子2:

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <signal.h>
    #include <sys/prctl.h>
    
    void my_system(void)
    {
        pid_t pid;
        pid = fork();
        if (pid == 0)
        {
         // 设置当父进程退出时,子进程也退出
    prctl(PR_SET_PDEATHSIG, SIGHUP); while (1) { printf("child running...\n"); sleep(1); } exit(0); } else if (pid < 0) { printf("create failed\n"); } } int main (int argc, char *argv[]) { int i = 0; my_system(); while (i++ < 6) { printf("father running...\n"); sleep(1); } printf("Main exit()\n"); return 0; }

    程序输出:

    [root@localhost ~]# ./a.out
    child running...
    father running...
    child running...
    father running...
    child running...
    father running...
    child running...
    father running...
    father running...
    child running...
    father running...
    child running...
    child running...
    Main exit()
    [root@localhost ~]#
    [root@localhost ~]#
    [root@localhost ~]#
    从程序输出可以看到当父进程退出了,那么子进程也就退出了。

  • 相关阅读:
    移动互联网整理笔记(这课内容太多了。。。)
    11.19
    hihoCoder#1879 : Rikka with Triangles (计算几何)
    hdu 4758 (AC自动机)
    hdu 4511 (AC自动机)
    2018 icpc 青岛
    hdu 6219 Empty Convex Polygons (凸包)
    2019 ccpc 秦皇岛
    2018 icpc 徐州
    hdu6599 I Love Palindrome String
  • 原文地址:https://www.cnblogs.com/Robotke1/p/3064932.html
Copyright © 2011-2022 走看看