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;
}
相关推荐
Amor风信子3 分钟前
华为OD机试真题---跳房子II
java·数据结构·算法
码农小白7 分钟前
linux驱动:(22)中断节点和中断函数
linux·运维·服务器
4647的码农历程8 分钟前
Linux网络编程 -- 网络基础
linux·运维·网络
戊子仲秋20 分钟前
【LeetCode】每日一题 2024_10_2 准时到达的列车最小时速(二分答案)
算法·leetcode·职场和发展
邓校长的编程课堂22 分钟前
助力信息学奥赛-VisuAlgo:提升编程与算法学习的可视化工具
学习·算法
sp_fyf_202439 分钟前
计算机前沿技术-人工智能算法-大语言模型-最新研究进展-2024-10-03
人工智能·算法·机器学习·计算机视觉·语言模型·自然语言处理
2401_8576100339 分钟前
SpringBoot实现:校园资料分享平台开发指南
服务器·spring boot·php
Eric.Lee20211 小时前
数据集-目标检测系列- 螃蟹 检测数据集 crab >> DataBall
python·深度学习·算法·目标检测·计算机视觉·数据集·螃蟹检测
C++忠实粉丝1 小时前
Linux环境基础开发工具使用(2)
linux·运维·服务器
林辞忧1 小时前
算法修炼之路之滑动窗口
算法