有名管道FIFO示例

shell中本身存在mkfifo的命令,但是本质也是调用mkfifo()函数实现。

与无名管道相比,无非是多了一个管道文件用以操作。

先在shell中通过mkfifo创建一个管道文件mkfifo s.pipe,执行read s.pipe和write s.pipe。

读端:

/*************************************************************************
    > File Name: read_fifo.c
    > Author: CC
    > Mail: [email protected] 
    > Created Time: 2018年09月08日 星期六 23时01分04秒
 ************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
int main(int argc,char *argv[])
{
	if(argc < 2){
		printf("Usage: %s fifo \n",argv[0]);
		exit(1);
	}

	printf("open fifo read .......\n");

	int fd = open(argv[1],O_RDONLY);
	if(fd < 0){
		perror("open fifo error!\n");
		exit(1);
	}else{
		printf("open file success: %d\n",fd);
	}
	//从命名管道中读取数据
	char buf[512];
	memset(buf,0,sizeof(buf));
	while(read(fd,buf,sizeof(buf)) < 0){
		perror("read error!\n");
		exit(1);
	}
	printf("read file %s\n",buf);
	close(fd);
	return 0;

}

写端:

/*************************************************************************
    > File Name: write_fifo.c
    > Author: CC
    > Mail: [email protected] 
    > Created Time: 2018年09月08日 星期六 23时07分51秒
 ************************************************************************/

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<string.h>

int main(int argc,char *argv[])
{
	if(argc < 2){
		printf("Usage: %s fifo\n",argv[0]);
		exit(1);
	}
	printf("open fifo write ......\n");

	int fd = open(argv[1],O_WRONLY);
	if(fd < 0){
		perror("write fifo error!\n");
		exit(1);
	}else{
		printf("write fifo success: %d\n",fd);
	}

	char *s = "ABCDEFG";
	size_t size = strlen(s);
	if(write(fd,s,size) != size){
		perror("write error!\n");
		exit(1);
	}
	close(fd);

	return 0;
}

与无名管道相同都是阻塞性的读写,适用于socket网络通信。

不同的是打开方式,无名管道通过pipe使用fcntl()系统调用设置O_NOBLOCK设置非阻塞读写。

FIFO通过fcntl()系统调用或者open()设置非阻塞性读写。

 

猜你喜欢

转载自blog.csdn.net/baidu_33879812/article/details/82534624