linux16.04 中创建 有名管道 fifo

创建一个有名管道,解决无血缘关系的进程之间的通信;

创建管道的函数

#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);

首先创建一个有名管道myfifo   命令是: mkfifo myfifo

也可以直接使用上边的函数直接在代码中实现管道。


然后分别创建两个“.c”文件,fifo_w.c  fifo_r.c 

fifo_w.c 
#include <stdio.h>#include <stdlib.h>#include <unistd.h>
#include <sys/stat.h>#include <fcntl.h>#include <string.h>
void sys_err(char *str, int exitno)
{
	perror(str);
	exit(exitno);
}
int main(int argc, char *argv[])
{
	int fd;
	char buf[1024] = "hello xuxing\n";
	if (argc < 2) {
		printf("./a.out filename\n");
		exit(1);
	}
	//fd = open(argv[1], O_RDONLY);
	fd = open(argv[1], O_WRONLY);
	if (fd < 0) {
		sys_err("open", 1);
	}
	write(fd, buf, strlen(buf));
	close(fd);
	return 0;
}

fifo_r.c 
#include <stdio.h>#include <stdlib.h>#include <unistd.h>
#include <sys/stat.h>#include <fcntl.h>#include <string.h>#include <sys/types.h>
void sys_err(char *str, int exitno)
{
	perror(str);
	exit(exitno);
}
int main(int argc, char *argv[])
{
	int fd, len;
	char buf[1024];

	if (argc < 2) {
		printf("./a.out filename\n");
		exit(1);
	}
	fd = open(argv[1], O_RDONLY);
	//fd = open(argv[1], O_WRONLY);
	if (fd < 0) {

		sys_err("open", 1);
	}
	len = read(fd, buf, sizeof(buf)); //读文件
	write(STDOUT_FILENO, buf, len);   //打印读取的内容
	close(fd);

	return 0;
}


运行结果:

 



创建的有名管道缓存的内容是不会存在磁盘中的。他只是在内核中的缓存中。







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值