用管道通信实现守护进程

来源:互联网 发布:英汉词典软件下载 编辑:程序博客网 时间:2024/05/29 16:18

创建两个进程,一个有名管道。一个进程如果正在运行就往管道里面发送运行信息,守护进程负责读取运行信息,一旦守护进程超过三秒读取不到运行信息,就自动将进程重启

守护进程代码:

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/types.h>#include <sys/stat.h>#include <errno.h>#include <fcntl.h>#define FIFO "/root/linux/myfifo"main(int argc, char** argv){        char buf[100];        int fd;        int nread;        int count = 0;        if((mkfifo(FIFO,O_CREAT|O_EXCL) < 0) &&(errno != EEXIST))       {                printf("creat fifo error!\n");        }        printf("perparing for reading bytes...\n");        memset(buf,0,sizeof(buf));            fd = open(FIFO,O_RDONLY|O_NONBLOCK,0);        if(fd == -1)        {                perror("open");        exit(1);        }        while(1)       {                memset(buf,0,sizeof(buf));        if(nread = read(fd,buf,100) <= 0)       {                    if(errno == EAGAIN)                {                          printf("no data yet\n");                 }                 count++;                     printf("read none\n");                 sleep(1);                 if(count == 3)                {                         printf("重新启动函数\n");                         system("./write success");                 count = 0;                }            }        else       {             printf("read %s from FIFO\n",buf);             sleep(1);        }       }       pause();       unlink(FIFO);}
守护进程代码:
#include <sys/types.h>#include <sys/stat.h>#include <errno.h>#include <fcntl.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#define FIFO_SERVER "/root/linux/myfifo"main(int argc, char** argv){        int fd;        char buf[100];        int nwrite;        fd = open(FIFO_SERVER,O_WRONLY|O_NONBLOCK,0);        if(argc == 1)        {        printf("please send st\n"); exit(-1);        }        strcpy(buf,argv[1]);        if((nwrite = write(fd,buf,100)) == 1)        {                if(errno == EAGAIN)       {                printf("not been read yet\n");       }               else              {                        printf("write %s to FIFO\n",buf);               }        }}


0 0
原创粉丝点击