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

当open一个FIFO时,是否设置非阻塞标志(O_NONBLOCK)的区别:
①若没有指定O_NONBLOCK(默认),只读open要阻塞到某个其他进程为写而打开此FIFO。类似的,只写open要阻塞到某个其他进程为读而打开它。
②若指定了O_NONBLOCK,则只读open立即返回,而只写open将出错返回-1如果没有进程已经为读而打开该FIFO,其errno置ENXIO。
例:
读的方式打开

#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;
}

读的方式打开

#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内容

//读的方式打开

#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;
}
//写的方式打开

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RT-Linux(实时Linux)是一个基于Linux内核的实时操作系统,它提供了对实时性的支持。RT-Linux使用内核级线程来实现实时性,它可以在Linux内核和实时任务之间提供良好的交互。编写RT-Linux应用程序与编写普通的Linux应用程序类似,但需要特别注意一些实时性相关的问题。 在RT-Linux中,可以使用POSIX实时扩展(也称为RTAI)或Xenomai框架来编写实时应用程序。这些框架提供了运行实时任务所需的API和机制,并与Linux内核进行交互。 编写RT-Linux应用程序需要考虑以下几个方面: 1. 实时任务的调度:在RT-Linux中,需要为实时任务设置优先级,并使用适当的调度策略来确保实时任务按时执行。常用的调度策略包括FIFO(先进先出)和RR(循环调度)。 2. 中断处理:实时应用程序通常需要与硬件设备进行交互,因此需要处理硬件中断。在RT-Linux中,可以使用中断处理程序来处理硬件中断,并采取适当的措施来保证实时性。 3. 实时性分析:为了确保实时任务能够按时执行,需要进行实时性分析。这包括确定任务的执行时间和响应时间,并根据实时性要求进行优化。 4. 同步和通信:在多个实时任务之间进行同步和通信是很常见的需求。RT-Linux提供了各种同步和通信机制,如信号量、互斥锁和消息队列等,可以用于实现任务之间的数据共享和通信。 总之,RT-Linux编程需要对实时性要求有一定的了解,并使用适当的编程技术和工具来满足这些要求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值