Linux 下有名(命名)管道文件读写操作

Linux 下有名(命名)管道文件读写操作

操作平台:Ubuntu 12.04

有名管道
1、查看命令:man 3 mkfifo
2、头文件:#include <sys/types.h>
#include <sys/stat.h>
3、函数原型:int mkfifo(const char *pathname, mode_t mode);
a、*pathname:有名管道的名字 例如:/home/whb/projects
b、 mode:八进制的权限, 例如:0777
4、返回值:成功:0 失败 -1

(1) 写数据的代码:

#include<iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<string.h>
#include <signal.h>
#define FIFO  "/home/whb/projects/11.fifo" //有名管道的名字

using namespace std;
int main()
{
	int result , fd;//result 为接收mkfifo的返回值   fd为打开文件的文件描述符
	char buffer[20] = { 0 };//定义一个字符数据
	if (access(FIFO, F_OK)==-1)//判断是否已经创建了有名管道,如果已经创建,则返回0 否则返回非0的数
	{
		result = mkfifo(FIFO, 0777);//创建有名管道,成功返回0,失败返回-1
		if (result < 0)
		{
			perror("creat mkfifo error");
			return 0;
		}
	}
	cout << "请输入数据:" << endl;
	//以只写方式打开有名管道,不能同时以读写权限打开,成功返回文件描述符,失败返回 - 1
	fd = open(FIFO,O_WRONLY);
	if (fd < 0)
	{
		perror("open error");
		return 0;
	}
	while (1)
	{
		fgets(buffer, sizeof(buffer), stdin);//从终端输入数据到buffer中
		write(fd, buffer, strlen(buffer));//数据写到有名管道
		memset(buffer, 0x0, sizeof(buffer));//清空缓存区
	}
	close(fd);//关闭有名管道
	return 0;
}

(2)读数据的代码:

#include<iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<string.h>
#include <signal.h>
#define FIFO  "/home/whb/projects/11.fifo"//有名管道的名字
using namespace std;

int main()
{
	int result ,fd;//result 接收mkfifo 的返回值  fd 文件描述符
	char buffer[20] = { 0 };
	if (access(FIFO, F_OK)==-1)//判断有名管道是否存在  不存在就创建  存在就不创建   已经创建返回0  否则非0
	{
		result = mkfifo(FIFO, 0777);//创建有名管道  0 成功   -1 失败
		if (result < 0)
		{
			perror("creat mkfifo error");
			return 0;
		}
	}
	fd = open(FIFO, O_RDONLY);//只读的方式打开  返回小于0的值为打开失败
	if (fd < 0)
	{
		perror("open error");
		return 0;
	}
	while (1)
	{
		read(fd, buffer, sizeof(buffer));
		cout << "buffer= " << buffer << endl;
		memset(buffer,0,sizeof(buffer));
	}
	close(fd);//关闭有名管道
	return 0;
}

运行效果如下:
在这里插入图片描述
如有写错情况,请大佬们留言指正,谢谢。


版权声明:本文为wangbaba_1原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
THE END
< <上一篇
下一篇>>