#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);   
    }   
}  

 

相关文章:

猜你喜欢
  • 2021-08-13
  • 2022-02-07
  • 2022-12-23
  • 2021-12-06
  • 2022-01-18
  • 2022-12-23
  • 2021-11-20
相关资源
相似解决方案