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;
}
相关推荐
倔强的小石头_2 分钟前
【C语言指南】函数指针深度解析
java·c语言·算法
Yasin Chen7 分钟前
C# Dictionary源码分析
算法·unity·哈希算法
sanggou1 小时前
Linux批量执行工具脚本使用指南:一键运行多个release-dev.sh脚本
linux·bash
_Coin_-1 小时前
算法训练营DAY27 第八章 贪心算法 part01
算法·贪心算法
段帅龙呀4 小时前
Redis构建缓存服务器
服务器·redis·缓存
乌鸦不像写字台4 小时前
【docker部署】在服务器上使用docker
服务器·docker·容器
牧以南歌〆5 小时前
在Ubuntu主机中修改ARM Linux开发板的根文件系统
linux·arm开发·驱动开发·ubuntu
董董灿是个攻城狮6 小时前
5分钟搞懂什么是窗口注意力?
算法
Dann Hiroaki6 小时前
笔记分享: 哈尔滨工业大学CS31002编译原理——02. 语法分析
笔记·算法
Antonio9156 小时前
【音视频】HLS简介与服务器搭建
运维·服务器·音视频