命名管道的创建与使用(mkfifo函数)

mkfifo函数(创建命名管道)

功能:

        它可以在不相关的进程之间进行通信,因为它有一个对应的文件名,存储在文件系统中,进程可以通过该文件名来访问它。

头文件:

#include <sys/types.h>
#include <sys/stat.h>

原型: 

int mkfifo(const char *pathname, mode_t mode);

参数: 

    pathname:这是一个字符串,指定了要创建的命名管道的文件路径和名称。

    mode:指定了命名管道的权限模式,类似于创建普通文件时的权限设置。例如,0666 表示所有用户都有读写权限。

返回值:

        如果函数调用成功,返回 0。

        如果调用失败,返回 -1,并设置 errno 以指示错误原因。常见的错误包括文件已存在、权限不足、路径无效等。

命名管道(非亲缘关系进程间使用)

一个解决方案中创建两个文件

        右击“解决方案”

        “添加”->“新建项目”

        和正常配置新项目一样,新建出来如下图所示

实例(Amain.cpp->Bmain.cpp):

Amain.cpp

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <cstring>

using namespace std;

int main()
{
	char buf[20] = { 0 };
	umask(0);

	// 创建命名管道
	if (access("/root/projects/AtoB.fifo",F_OK) == -1) // 判断文件是否存在
	{
		// 文件不存在就创建管道
		if (mkfifo("/root/projects/AtoB.fifo", 0777) == -1)
		{
			// 管道创建失败
			perror("mkfifo error");
		}
		else
		{
			// 管道创建成功
			cout << "AtoB.fifo create success" << endl;
		}
	}
	else
	{
		// 存在就不用创建
		cout << "AtoB.fifo already exists" << endl;
	}

	// 连接管道(管道必须打通读写才会完成管道的建立)
	int fd = open("/root/projects/AtoB.fifo", O_WRONLY); // 写方式打开管道
	while (1)
	{
		cin >> buf;

		int res = write(fd, buf, sizeof(buf));
		cout << "A进程发送了= " << res << "个字节" << endl;

		bzero(buf, sizeof(buf));
	}

	close(fd);

	return 0;
}

Bmain.cpp

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <cstring>

using namespace std;

int main()
{
	char buf[20] = { 0 };
	umask(0);
	if (access("/root/projects/AtoB.fifo", F_OK) == -1)
	{
		if (mkfifo("/root/projects/AtoB.fifo", 0777) == -1)
		{
			perror("mkfifo error");
		}
		else
		{
			cout << "AtoB.fifo create success" << endl;
		}
	}
	else
	{
		cout << "AtoB.fifo already exists" << endl;
	}

	int fd = open("/root/projects/AtoB.fifo", O_RDONLY);
	while (1)
	{
		int res = read(fd, buf, sizeof(buf));
		cout << "B进程收到了= " << res << "个字节,buf=" << buf << endl;

		bzero(buf, sizeof(buf));
	}

	close(fd);

	return 0;
}

结果:

注意事项: 

        使用open时只能是一个文件读一个文件写,不能既读又写。

        但其实并不依赖fifo文件(用文件名给管道命名,但文件没有操作),管道创建后跟文件就没有关系了。如下图所示,我上面代码中创建出的fifo文件,它的大小是0KB。这就说明了我上句话,命名管道并不依赖fifo文件进行传输就是一个虚假行为

        缺陷:管道上限65535字节≈64KB 。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值