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;
}
相关推荐
Linux技术芯5 分钟前
Linux内核内存管理 ARM32内核内存布局的详细解析和案例分析
linux
烨鹰5 分钟前
戴尔电脑安装Ubuntu双系统
linux·运维·ubuntu
月亮被咬碎成星星9 分钟前
LeetCode[15]三数之和
数据结构·算法·leetcode
mzak17 分钟前
vscode集成deepseek实现辅助编程(银河麒麟系统)【详细自用版】
linux·vscode·编辑器·银河麒麟·deepseek
haoranyyy22 分钟前
mac环境中Nginx安装使用 反向代理
linux·服务器·nginx
JCBP_26 分钟前
数据结构3
服务器·c语言·数据结构·vscode
HX科技28 分钟前
Debian系统_主板四个网口1个配置为WAN,3个配置为LAN
linux·运维·网络·debian
半盏茶香40 分钟前
启幕数据结构算法雅航新章,穿梭C++梦幻领域的探索之旅——堆的应用之堆排、Top-K问题
java·开发语言·数据结构·c++·python·算法·链表
小竹子141 小时前
L1-1 天梯赛座位分配
数据结构·c++·算法
董董灿是个攻城狮1 小时前
Transformer 通关秘籍8:词向量如何表示近义词?
算法