Linux进程间通信之二:命名管道fifo

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值