README
创建了两个掩藏的命名管道文件(.fifo_chat1和.fifo_chat2)在不同的进程间进行双向通信,实现全双工方式通信
https://blog.csdn.net/ZHNEYU/article/details/126044287
fifo.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <libgen.h>
#include <wait.h>
#define FIFO_FILE1 ".fifo_chat1"
#define FIFO_FILE2 ".fifo_chat2"
int stop = 0;
void sig_pipe(int signum)
{
if(SIGPIPE == signum)
printf("SIGPIPE really get...\n");
stop = 1;
}
int main(int argc,char **argv)
{
int mode = -1;
int rfd=-1,wfd=-1;
fd_set rdset;
char buf[128];
int res = -1;
if(NULL == argv[1]){
printf("Usage:./%s [0/1]",basename(argv[0]));
printf("\nThis chat program need run twice,must select arguments among 0 or 1 in difference!!!\n");
return -1;
}
if(access(FIFO_FILE1,F_OK)<0){//判断文件是否存在
mkfifo(FIFO_FILE1,0666);
printf("%s create success...\n",FIFO_FILE1);
}
if(access(FIFO_FILE2,F_OK)<0){//判断文件是否存在
mkfifo(FIFO_FILE2,0666);
printf("%s create success...\n",FIFO_FILE2);
}
signal(SIGPIPE,sig_pipe);//安装信号,SIGPIPE(13)
mode = atoi(argv[1]);
if(0==mode){//fifo1 r,fifo2 w
printf("mode[0] open '%s' to read...\n",FIFO_FILE1);
rfd = open(FIFO_FILE1,O_RDONLY);
printf("mode[0] open '%s' to write...\n",FIFO_FILE2);
wfd = open(FIFO_FILE2,O_WRONLY);
}else if(1==mode){//fifo1 w,fifo2 r
printf("mode[1] open '%s' to write...\n",FIFO_FILE1);
wfd = open(FIFO_FILE1,O_WRONLY);
printf("mode[1] open '%s' to read...\n",FIFO_FILE2);
rfd = open(FIFO_FILE2,O_RDONLY);
}
while(!stop){
FD_ZERO(&rdset);
FD_SET(STDIN_FILENO,&rdset);
FD_SET(rfd,&rdset);
res = select(rfd+1,&rdset,NULL,NULL,NULL);
printf("Wake up...\n");
if(res<0){
printf("select() failure or get timeout:%s\n",strerror(errno));
break;
}
if(FD_ISSET(STDIN_FILENO,&rdset)){//当前进程 有STD输入
memset(buf,0x00,sizeof(buf));
/* 从标准输入端读取内容,并写入管道*/
fgets(buf,sizeof(buf),stdin);
write(wfd,buf,sizeof(buf));
}else if(FD_ISSET(rfd,&rdset)){//当前进程 读取到fifo1有输入
res = read(rfd,buf,sizeof(buf));
if(res<0){
printf("read data in chat failure:%s\n",strerror(errno));
break;
}else if(res==0){
printf("another side of fifo is closed...\n");
break;
}
printf("<--%s",buf);
}
}
return 0;
}