Linux命名管道

//命名管道特点:
//1.如果打开管道的一方仅以读或写的方式打开管道,必须需要另一方的介入,管道才能打开
//双方都调用open
//可以一方打开,以读写的方式打开open(DEF_FIFO_PATH,O_RDWR)
//发送少量简单无格式的数据
//双方读写都存在,才能打开管道
//计时性存储数据
//2.存在的文件
//3.单向写入,单向写出
//问答形式

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>

#define DEF_FIFO_PATH ("./FIFO")
#define DEF_STD_ERROR (-1)

int main(int argc,char *argv[])
{
        int ret;
        int fd;
        char str[1024];
        //if argv[1] > 0,writer
        if(atoi(argv[1])>0)
		{
			ret = mkfifo(DEF_FIFO_PATH,S_IWUSR | S_IRUSR);
			if(ret == DEF_STD_ERROR)
			{
					if(errno == EEXIST)
					{
							printf("Fifo always exist\n");
					}
					else
					{
							printf("%d\n",strerror(errno));
							return -1;
					}
			}
			//open fifo
			fd = open(DEF_FIFO_PATH,O_WRONLY)//O_WRONLY紧以读的方式打开,两个进程
			if(fd == DEF_STD_ERROR)
			{
					printf("%d\n",strerror(errno));
					//delete pipe打开失败删除文件(管道)
					unlink(DEF_FIFO_PATH);
					return -1;
			}
			//write
			while(1)
			{
					printf("Please input string:\n");
					scanf("%s",str);
					write(fd,str,strlen(str)+1);
					if(!strcmp(str,"goodbye"))
					{
							break;
					}
			}
			//close fifo
			close(fd);
	}
    else 
	{
			//if argv[1] <= 0,reader
			//check fifo
			ret = access(DEF_FIFO_PATH,W_OK);
			if(ret == DEF_STD_ERROR)
			{
					printf("%d\n",strerror(errno));
					return -1;
			}
			//open fifo
			fd = open(DEF_FIFO_PATH,O_RDONLY);
			if(fd == DEF_STD_ERROR)
			{
					printf("%d\n",strerror(errno));
					return -1;
			}
			//read fifo
			while(1)
			{
					read(fd,str,sizeof(str));
					printf("Receive data:[%s]\n",str);
					if(strcmp("goodbye",str)==0)
					{
							break;
					}
			}
			//close fifo
			close(fd);
	}
        return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值