前一个程序虽然能实现简单的通信,但仍然存在不足
1.在其中一个中断按CTDL+C退出时,另一个中断会失控,那么用什么来解决这个呢,这就使用到信号量,当进程截获到ctrl+c信号的时候,给父子进程都发送usr信号,子进程退出,被父进程杀死,之后父进程再自己退出
client:
#include <stdio.h> #include <stdlib.h> #include<sys/stat.h> #include<sys/types.h> #include<fcntl.h> #include<string.h> #include<unistd.h> #include<sys/wait.h> void stop() { kill(getpid(),10); kill(getppid(),12); } void childstop() { puts("子进程退出"); exit(0); } void fatherstop() { puts("父进程退出"); exit(0); } int main() { pid_t pid; int rfd,wfd; char buf[1024]; int len; umask(0); signal(SIGINT,stop); pid=fork(); if(pid>0) {signal(10,fatherstop); while(1) { wfd=open("rdfifo",O_RDWR); if(wfd==-1) { perror("client write wrong"); } memset(buf,0,100);//每次使用的时候都清空以下buf printf("client:"); fgets(buf,1024,stdin); //buf[strlen(buf)-1]='\0'; if(strcmp(buf,"quit")==0) { close(rfd); unlink("rdfifo"); wait(NULL); exit(0); } write(wfd,buf,strlen(buf)); } } else { signal(10,childstop); while(1) { while((rfd=open("wrfifo",O_RDONLY))==-1); memset(buf,0,1024);//每次使用的时候都清空以下buf len=read(rfd,buf,1024); if(len==-1) { perror("client read wrong"); } else { buf[len]='\0'; printf("server:%s",buf); } } } exit(0); }
server:
#include <stdio.h> #include <stdlib.h> #include<sys/stat.h> #include<sys/types.h> #include<fcntl.h> #include<string.h> #include<unistd.h> #include<sys/wait.h> void stop() { kill(getpid(),10); kill(getppid(),12); } void childstop() { puts("子进程退出"); exit(0); } void fatherstop() { puts("父进程退出"); exit(0); } int main(int argc,char **argv) { pid_t pid; int wfd,rfd; char buf[1024]; int len; umask(0); signal(SIGINT,stop); //signal(SIGINT,SIG_IGN); //要设置一下当遇到ctrl+c信号时以什么结束父子进程为信号 pid=fork(); if(pid==0) { signal(10,childstop); while(1) { while((rfd=open("rdfifo",O_RDONLY))==-1){} memset(buf,0,100);//每次使用的时候都清空以下buf len=read(rfd,buf,1024); if(len==-1) { perror("server write wrong"); exit(1); } else { // buf[len]='\0'; printf("Client:%s",buf); } } } else if(pid>0) { signal(10,fatherstop); while(1) { wfd=open("wrfifo",O_RDWR); if(wfd==-1) { perror("open pipe wrfifo wrong!"); exit(1); } memset(buf,0,100);//每次使用的时候都清空以下buf printf("server:"); fgets(buf,1024,stdin);//从标准输入获取 //buf[strlen(buf)-1]='\0'; if(strcmp(buf,"q")==0) { close(wfd); unlink("wrfifo"); exit(0); } write(wfd,buf,strlen(buf)); } } exit(0); }
这样之后强制退出时便不会产生影响。