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

相关博客

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
#include
#include
#include

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


运行结果:


关于子进程异步等待方式(SIGCHLD信号)_第1张图片

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


#include
#include
#include
#include

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

运行结果:


关于子进程异步等待方式(SIGCHLD信号)_第2张图片

你可能感兴趣的:(Linux,linux学习)