异步回收fork出的子进程(僵尸进程)

#include <stdio.h>   
#include <stdlib.h>   
#include <signal.h>   
#include <unistd.h>   
#include <sys/wait.h>   
    
void handler(int num) {   
    //我接受到了SIGCHLD的信号啦   
    int status;   
    int pid = waitpid(-1, &status, WNOHANG);   
    if (WIFEXITED(status)) {   
        printf("The child %d exit with code %d\n", pid, WEXITSTATUS(status));   
    }   
}   
    
int main() {   
    //子进程的pid   
    int c_pid;   
    int pid;   
    
    signal(SIGCHLD, handler);   
    
    if ((pid = fork())) {   
        //父进程   
        c_pid = pid;   
        printf("The child process is %d\n", c_pid);   
    
        //父进程不用等待,做自己的事情吧~   
        for (int i = 0; i < 10; i++) {   
            printf("Do parent things.\n");   
            sleep(1);   
        }   
    
        exit(0);   
    } else {   
        //子进程   
        printf("I 'm a child.\n");   
        sleep(2);   
        exit(0);   
    }   
}  

 

posted on 2017-03-14 13:40  dongruiha  阅读(1020)  评论(0编辑  收藏  举报

导航