Linux--数据通信编程实现(FIFO)

当open一个FIFO时,是否设置非阻塞标志(O_NONBLOCK )的区别:

①若没有指定O_NONBLOCK(默认),只读open要阻塞到某个其他进程为写而打开此FIFO。类似的,只写open要阻塞到某个其他进程为读而打开它。

②若指定了O_NONBLOCK,则只读open立即返回,而只写open将出错返回-1如果没有进程已经为读而打开该FIFO,其errno置ENXIO。
例:

读的方式打开

c 复制代码
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.c>
 
//	int mkfifo(const char *pathname, mode_t mode);
 
int main()
{
	if((mkfifo("./file",0600)==-1)&&errno!=EEXIST){
		printf("mkfifo failuer \n");
		perror("why?\n");
	}
 	
 	int fd = open("./file",O_RDONLY);
 	printf("open success\n");
 	//用写的方式打开FIFO,读才不会阻塞
	return 0;
}

读的方式打开

c 复制代码
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.c>
 
//	int mkfifo(const char *pathname, mode_t mode);
 
int main()
{
 	int fd = open("./file",O_WRONLY);
 	printf("write open success\n");
 	//用写的方式打开FIFO,读才不会阻塞
	return 0;
}

运行read会发生阻塞,调用write之后程序继续进行。

例:读取FIFO内容

c 复制代码
//读的方式打开

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.c>
 
//	int mkfifo(const char *pathname, mode_t mode);
 
int main()
{
	int buf[30] = {0};
	
	if((mkfifo("./file",0600) == -1) && errno != EEXIST){
		printf("mkfifo failuer \n");
		perror("why?\n");
	}
 	
 	int fd = open("./file",O_RDONLY);
 	printf("open success\n");
 	//用写的方式打开FIFO,读才不会阻塞
	
	int nread = read(fd,buf,20);
	printf("read %d byte from fifo , context : %s\n",nread,buf);
	
	close(fd);
	
	return 0;
}
c 复制代码
//写的方式打开

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.c>
 
//	int mkfifo(const char *pathname, mode_t mode);
 
int main()
{
	char *str = "message from FIFO !";
	
 	int fd = open("./file",O_WRONLY);
 	printf("write open success\n");
 	//用写的方式打开FIFO,读才不会阻塞
	
	write(fd,str,strlen(str));
	
	close(fd);
	
	return 0;
}
相关推荐
卷福同学14 分钟前
【AI编程】AI+高德MCP不到10分钟搞定上海三日游
人工智能·算法·程序员
mit6.82415 分钟前
[Leetcode] 预处理 | 多叉树bfs | 格雷编码 | static_cast | 矩阵对角线
算法
渡我白衣22 分钟前
Linux操作系统之进程间通信:共享内存
linux
总有刁民想爱朕ha27 分钟前
零基础搭建监控系统:Grafana+InfluxDB 保姆级教程,5分钟可视化服务器性能!
运维·服务器·grafana
皮卡蛋炒饭.37 分钟前
数据结构—排序
数据结构·算法·排序算法
Mr_Orangechen1 小时前
Linux 下使用 VS Code 远程 GDB 调试 ARM 程序
linux·运维·arm开发
??tobenewyorker1 小时前
力扣打卡第23天 二叉搜索树中的众数
数据结构·算法·leetcode
Shartin2 小时前
Can201-Introduction to Networking: Application Layer应用层
服务器·开发语言·php
贝塔西塔2 小时前
一文读懂动态规划:多种经典问题和思路
算法·leetcode·动态规划
lilian1292 小时前
linux系统mysql性能优化
linux·运维·mysql