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;
}
相关推荐
郝亚军10 分钟前
asqlite-autoconf-3310100 的ubuntu 22.04 aarch64交叉编译
linux·运维·ubuntu
过去式的美好12 分钟前
阿里云 2 核 2G 服务器搭建 AI 知识库:从 0 到可用(附踩坑实录)
服务器·人工智能·阿里云
show43320 分钟前
2026小程序端AI智能优化技术实践:转文字后自动纠错+润色+分段算法分析
人工智能·算法·小程序
如意机反光镜裸28 分钟前
如何合并局域网共享文件夹中的多个 Excel 工作簿?(免 WPS 会员解决方案)
服务器·excel·wps
笑锝没心没肺33 分钟前
Linux安装docker及运行容器测试
linux·运维·docker
数据知道38 分钟前
网络安全实战:渗透测试全流程 SOP——从授权到报告交付
服务器·网络·安全·web安全·网络安全
Mr_liu_66640 分钟前
Claude非专业入门实战笔记(附录):关闭Telemetry-遥测,消除无用网络请求与日志噪音
linux·笔记·ubuntu·ai编程
时空无限1 小时前
ubuntu apt 查看软件之间的依赖
linux·运维·ubuntu
平生不晚1 小时前
在 SVG 体系里画一条任意的线
前端·算法
Escalating_xu1 小时前
【Linux】线程概念与控制:从地址空间、LWP 到 pthread_create、join、detach 与 NPTL
java·linux·redis