1. 程式人生 > >父程序異常退出時, 殺死所以子程序

父程序異常退出時, 殺死所以子程序

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/prctl.h>
#include <signal.h>
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<string.h> #include<sys/prctl.h> #include<signal.h> #include
<unistd.h> #include <stdlib.h> 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; }