Linuxkiss
    首页 Linux C/C++ C++面试 Qt答疑 Qml中文手册 Qt CMake Python 工具
Linuxkiss
www.linuxkiss.com 你可以精通一门IT技术
  1. 首页
  2. Linux
  3. 正文

fifo无血缘关系读写操作

2016年06月02日 13点热度 0人点赞

fifo管道间无血缘关系读写操作,下面直接上代码。

read.c

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

/*
 * 进程 A -- 读操作 -- fifo
 */

int main(int argc, char *argv[])
{
	if(argc < 2)
	{
		printf("./a.out fifoname\n");
		exit(1);
	}

	// 判断文件是否存在
	int ret = access(argv[1], F_OK);
	if(ret == -1)
	{
		// 创建管道
		int r = mkfifo(argv[1], 0664);
		if(r == -1)
		{
			perror("mkfifo");
			exit(1);
		}
		else
		{
			printf("有名管道创建成功!\n");
		}
	}

	// 打开管道
	int fd = open(argv[1], O_RDONLY);
	if(fd == -1)
	{
		perror("open");
		exit(1);
	}

	// 读管道
	while(1)
	{
		char buf[1024];
		read(fd, buf, sizeof(buf));
		printf("buf = %s\n", buf);
	}
	close(fd);
	return 0;
}

write.c

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

/*
 * 进程 B -- 写操作 -- fifo
 */

int main(int argc, char *argv[])
{
	if(argc < 2)
	{
		printf("./a.out fifoname\n");
		exit(1);
	}

	// 判断文件是否存在
	int ret = access(argv[1], F_OK);
	if(ret == -1)
	{
		// 创建管道
		int r = mkfifo(argv[1], 0664);
		if(r == -1)
		{
			perror("mkfifo");
			exit(1);
		}
		else
		{
			printf("有名管道创建成功!\n");
		}
	}

//写操作

	int fd = open(argv[1],O_WRONLY);
	if(fd == -1)
	{
		perror("open");
		exit(1);
	}
	//写管道

	while(1)
	{
		char str[100];
		scanf("%s",str);
	//char *p = "hello word!";
	write(fd,str,strlen(str)+1);
	 
	} 
	close(fd);
	return 0;
}

代码写完,分别在两个终端进行编译执行这两个进程。

终端一:

//编译读文件
gcc read.c -o read

//执行读文件,带上abc这个管道
./read abc

终端二:

//编译写文件
gcc write.c -o write

//执行写文件,带上abc这个管道
./write abc

//在该终端输入字符串回车
...
...

 

标签: Linux
最后更新:2020年04月21日

Leo

保持饥渴的专注,追求最佳的品质

点赞
< 上一篇
下一篇 >
关注公众号

日历
2021年4月
一 二 三 四 五 六 日
« 2月    
 1234
567891011
12131415161718
19202122232425
2627282930  
最新 热点 随机
最新 热点 随机
windows中出现"无法解析的外部符号"到底是什么原因 Qt5中lambda表达式用法,非常实用 warning: class 'InterFace' defines a non-default destructor but does not define a copy constructor, a copy assignment operator, a move constructor or a move assignment operator 无法解析的外部符号 "public: static struct QMetaObject const Windows下Qt代码出现的错误总结 QT Creator如何在创建项目的时候,头文件和cpp文件的首字母默认大写
6.1 软件包管理简介 C++中const有什么作用 qmake高级用法--库的依赖关系(Library Dependencies) ubuntu16.04出现The system is running in low-graphics mode【已解决】 opencv系列12--形态学操作应用-提取水平与垂直线 [ api:adaptiveThreshold ] C++头文件引用中和“”的区别?
标签聚合
C++ C/C++面试 qml中文手册 qmake openCv Qt Linux qml中文文档

COPYRIGHT © 2020 Linuxkiss. ALL RIGHTS RESERVED.