异步回收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
", 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
", c_pid);   
    
        //父进程不用等待,做自己的事情吧~   
        for (int i = 0; i < 10; i++) {   
            printf("Do parent things.
");   
            sleep(1);   
        }   
    
        exit(0);   
    } else {   
        //子进程   
        printf("I 'm a child.
");   
        sleep(2);   
        exit(0);   
    }   
}  
原文地址:https://www.cnblogs.com/dongruiha/p/6548064.html