有名管道读写代码

一、读代码:

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

#define FIFOTMP "./fifotmp"
#define MAXLINE 1024

int main(int argc,int *argv[])
{
	int fd;
	char buf[MAXLINE];
	int nread;
	if(argc > 1)
		printf("please try again!\n");
	if((fd = open(FIFOTMP,O_RDONLY,0644)) == -1)//以阻塞方式打开
	{
		perror("error");
		exit(1);
	}
	memset(buf,0,sizeof(buf));
	if((nread = read(fd,buf,MAXLINE)) == -1
	else 
		printf("read the data %s",buf);
	exit(0);
}


二、写代码

 

#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#define FIFOTMP "./fifotmp"
#define MAXLINE 1024
int main(int argc,char **argv)
{
	int fd;
	char buf[MAXLINE];
	int nwrite;
	if(mkfifo(FIFOTMP,O_CREAT|O_EXCL < 0) && (errno != EEXIST))
	{
		printf("creat error...\n");
	}
	fd = open("./fifotmp",O_WRONLY|O_NONBLOCK,0);	//以写方式打开
	if(fd < 0 )
		perror("open error:");
	memset(buf,0,MAXLINE);
	strcpy(buf,argv[1]);
	if((nwrite = write(fd,buf,MAXLINE)) == -1)
		perror("write error:");
	else 
		printf("write %s bytes",buf);
	exit(0);
	
}


三、总结

1、其中读进程是以阻塞的方式打开管道,那么如果此时只运行./read_fifo那么会一直在read的处等待知道管道中有数据,而假如程序改为以非阻塞的方式打开那么将直接返回。

2、程序中的写管道是以非阻塞的方式打开的,那么如果读进程没有打开,直接运行写进程将直接出错,而打不开管道文件(原因在第三点)(错误码是no such device or address),如果先打开读进程且读进程在等待,那么当写进程一旦写入数据读进程即可读到!

3、

FIFO的打开规则:

如果当前打开操作是为读而打开FIFO时,若已经有相应进程为写而打开该FIFO,则当前打开操作将成功返回;否则,可能阻塞直到有相应进程为写而打开该FIFO(当前打开操作设置了阻塞标志);或者,成功返回(当前打开操作没有设置阻塞标志)。(上例可验证)。

如果当前打开操作是为写而打开FIFO时,如果已经有相应进程为读而打开该FIFO,则当前打开操作将成功返回;否则,可能阻塞直到有相应进程为读而打开该FIFO(当前打开操作设置了阻塞标志);或者,返回ENXIO错误(当前打开操作没有设置阻塞标志)。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值