Linux的僵尸进程处理2

linux下的僵尸进程处理例子,同时也演示了管道通信的弊端

/*************************************************************************
        > File Name: ft.c
        > Author: zhoulin
        > Mail: 715169549@qq.com
        > Created Time: Fri Mar 25 15:21:00 2016
 ************************************************************************/

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
void deal(int sig){
    fprintf(stdout,"        *******cur %d exit*******\n",getpid()); //Ctrl+C的发送信号的处理(SIGINT信号)
    exit(1);
}
int main(void)
{
    pid_t f;
    int fd[2]; //管道通信,ffd[0]用于读,fd[1]用于写
    if(pipe(fd) <0){
        perror("pipe");
        return -1;
    }
    f= fork();
    if(f < 0){
        perror("fork");
        return -1;
    }
    if(f > 0){
        char buf[32] = {'\0'};
        signal(SIGINT,&deal); //信号注册
        while(1)
        {
            memset(buf,'\0',32);
            fprintf(stdout,"        ******parent %d********\n",getpid());
            system("ps -ef |grep -v 'grep'|grep -v 'ksoftirqd'|grep 'ft'");
            sleep(1);
            close(fd[1]);
            if(read(fd[0],buf,32) < 0) //接受子进程过来的信息
            {
                perror("read");
                return -1;
            }
            if(strlen(buf) > 0){
                fprintf(stdout,"    ----------------%s-------------\n",buf);
                if(strncmp(buf,"active",6) == 0){
                    fprintf(stdout,"        *****child is running*****\n");
                }
                if(strncmp(buf+6,"die",3) == 0) {
                    fprintf(stdout,"        *****child is die*****\n");
                    system("ps -ef |grep -v 'grep'|grep -v 'ksoftirqd'|grep 'ft'");
                    int status;
                    fprintf(stdout,"    ****recyle child %d******\n",wait(&status));
                }
            }
        }
    }else {
        int i = 0;
        while(1){
            close(fd[0]);
            fprintf(stdout,"        ******child %d********\n",getpid());
            system("ps -ef |grep -v 'grep'|grep -v 'ksoftirqd'|grep 'ft'");
            sleep(1);
            i++;
            if(i == 3){
                fprintf(stdout,"        #####child exit#####\n");
                write(fd[1],"die",3); //发送消息给父进程,要推出啦
                exit(0);
            }
            if(write(fd[1],"active",6) < 0){
                perror("write");
                return -1;
            }
        }
    }
    return 0;
}

 

运行结果:

 

posted @ 2016-03-25 16:26  一个万能盒子叫数据库  阅读(262)  评论(0编辑  收藏  举报