Linux——进程间通信(命名管道FIFO)

1.特点
①.FIFO可以在无关的进程之间交换数据
②.FIFO有路径名与之相关联,它以一种特殊设备文件形式存在于文件系统中。

2.原型
 #include <sys/types.h>
 #include <sys/stat.h>

 int mkfifo(const char *pathname, mode_t mode);

错误返回-1,成功返回0

简单理解可以说是创造一个管道,可以用read,write等对管道进行一个读写,从而实现通信
其中的 mode 参数与open函数中的 mode 相同。一旦创建了一个 FIFO,就可以用一般的文件I/O函数操作它。

当 open 一个FIFO时,是否设置非阻塞标志(O_NONBLOCK)的区别:

若没有指定O_NONBLOCK(默认),只读 open 要阻塞到某个其他进程为写而打开此 FIFO。类似的,只写 open 要阻塞到某个其他进程为读而打开它。

若指定了O_NONBLOCK,则只读 open 立即返回。而只写 open 将出错返回 -1 如果没有进程已经为读而打开该 FIFO,其errno置ENXIO

3.例子
FIFO的通信方式类似于在进程中使用文件来传输数据,只不过FIFO类型文件同时具有管道的特性。在数据读出时,FIFO管道中同时清除数据,并且“先进先出”。
简单实现一个单向通信demo,write端可以不断写,read端可以实时读取在终端显示

认识一个API:memset是一个初始化函数,作用是将某一块内存中的全部设置为指定的值

demo_read.c

void *memset(void *s, int c, size_t n); 

  • s指向要填充的内存块。
  • c是要被设置的值。
  • n是要被设置该值的字符数。
  • 返回类型是一个指向存储区s的指针
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include<stdlib.h>
#include <string.h>
int main()
{
	int ret;
	int fd;
	char *read_buff;

	read_buff = (char *)malloc(1024);

	ret = mkfifo("./file_fifo",0600);
	if(ret == -1 && errno !=EEXIST){
		printf("mkfifo failed\n");
		perror("why");
	}else if(ret == 0){
		printf("mkfifo sucess!\n");
	}
	fd = open("./file_fifo",O_RDONLY);
	while(1){
	read(fd,read_buff,1024);
	printf("read_buff:%s\n",read_buff);
	memset(read_buff,0,strlen(read_buff));
	}
	close(fd);
	return 0;
}

demo_write.c

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

int main()
{
	int fd_w;
	char *write_buff;
	int size;
	
	write_buff = (char *)malloc(1024);

	fd_w = open("./file_fifo",O_WRONLY);
	while(1){
	scanf("%s",write_buff);
	size = strlen(write_buff);
	write(fd_w,write_buff,size);
	memset(write_buff,0,size);
	}
	close(fd_w);
	return 0;
}

效果:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值