父进程异常退出时, 杀死所以子进程

 
    
#include 
#include 
#include 
#include 
#include 
#include 



void my_system(const char*cmd)
{
    pid_t pid;
    pid = fork();
    if (pid == 0)
    {
        prctl(PR_SET_PDEATHSIG, SIGHUP);
        execl("/bin/bash", "/bin/bash", "-c", cmd, NULL);
        exit(0);
    } else if (pid < 0)
    {
        printf("create failed\n");
    }
}

int main()
{
    int i = 0;
    my_system("./tstprogram");
    while (5)
    {
        printf("a\n");
        sleep(1);
        i++;
    }
    return 0;
}

#include
#include
#include
#include
#include 

static int do_abort = 0;

void handle_signal(int signo) {
    if (signo == SIGHUP) {
        printf("child recv SIGHUP..\n");
        do_abort = 1;
    }
}

int main(void) {
    pid_t pid;
    pid = fork();
    char *p = NULL;
    if (pid == 0) {
        signal(SIGHUP, handle_signal);
        prctl(PR_SET_PDEATHSIG, SIGHUP);
        while (!do_abort) {
            sleep(1);
            printf("in child...%d\n", getpid());
        }
        printf("child exit...%d\n", getpid());
        exit(0);
        return 0;
    }
    else {
        int times = 5;
        while (times-- > 0) {
            sleep(1);
            if (times == 3) {
                printf("memcpy ...\n");
                memcpy(p, "Hello", 5);
            }
            printf("in parent.%d\n", getpid());
        }
        printf("parent exit..\n");
        return 0;
    }
    return 0;
}

你可能感兴趣的:(父进程异常退出时, 杀死所以子进程)