关于子进程异步等待方式(SIGCHLD信号)

来源:互联网 发布:想购买个4星的淘宝店铺 编辑:程序博客网 时间:2024/06/09 18:18

相关博客

Linux下的信号(一)

http://blog.csdn.NET/double_happiness/article/details/72848372

Linux下的信号(二)

http://blog.csdn.Net/double_happiness/article/details/72897148


僵尸进程

http://blog.csdn.net/double_happiness/article/details/70168897


在上面关于僵尸进程的父进程等待时,父进程有两种等待方式,即阻塞和非阻塞,下面我们来验证一下,子进程退出时的其他情况


验证子进程退出时会给父进程发送信号


#include<stdio.h>#include<signal.h>#include<stdlib.h>#include<sys/types.h>void handler(int sig){        printf("sig is %d,pid is %d\n",sig,getpid());}int main(){        signal(SIGCHLD,handler);        int id=fork();        if(id<0){                perror("fork");                exit(-1);        }        else if(id==0){                sleep(3);                printf("i am child, my pid is %d\n",getpid());                exit(2);        }        else{                while(1){                        printf("i am parent,my pid is %d\n",getpid());                        sleep(1);                }        }        return 0;}


运行结果:



父进程等待子进程的异步版本代码实现:


#include<stdio.h>#include<signal.h>#include<stdlib.h>#include<sys/types.h>void handler(int sig){        printf("sig is %d,pid is %d\n",sig,getpid());}int main(){        int id=fork();        if(id<0){                perror("fork");                exit(-1);        }        else if(id==0){                sleep(3);                printf("i am child, my pid is %d\n",getpid());                exit(2);        }        else{                struct sigaction act;                act.sa_handler = handler;                sigemptyset(&act.sa_mask);                act.sa_flags = 0;                sigaction(SIGCHLD, &act, NULL);                while(1){                        printf("i am parent,my pid is %d\n",getpid());                        sleep(1);                }        }        return 0;}

运行结果:



原创粉丝点击