linux之通过FIFO完成两个非血缘关系进程间的通信

本文介绍了Linux中的FIFO(First-In-First-Out,先进先出)机制,如何通过mkfifo创建、使用以及它在非亲缘进程间通信中的作用。通过代码示例展示了创建FIFO、向其写入数据和读取数据的过程,以及如何实现两个独立进程的数据交换。
摘要由CSDN通过智能技术生成

1.FIFO 常被称为命名管道,以区分管道(pipe)。管道(pipe)只能用于“有血缘关系”的进程间。但通过 FIFO,不相关的进程也能交换数据。

2.FIFO 是 Linux 基础文件类型中的一种。但,FIFO 文件在磁盘上没有数据块,仅仅用来标识内核中一条通道。各进程可以打开这个文件进行 read/write,实际上是在读写内核通道,这样就实现了进程间通信。

3.创建方式:

        a.命令:mkfifo 管道名

        b.库函数:int mkfifo(const char *pathname, mode_t mode); 成功:0; 失败:-1

4.一旦使用 mkfifo 创建了一个 FIFO,就可以使用 open 打开它,常见的文件 I/O 函数都可用于 fifo。如:close、read、write、unlink 等。

5.使用mkfifo函数创建一个FIFO,代码:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/types.h>

void sys_err(const char *str)
{
	perror(str);
	exit(1);
}

int main(int argc, char *argv[])
{
	int ret = mkfifo("mytestfifo",0664);
	if(ret==-1)
		sys_err("mkfifo error");

	return 0;
}

6. 通过上面创建好的FIFO文件 mytestfifo 完成两个非血缘关系进程间的通信,一个进程向mytestfifo中写数据,另一个进程从mytestfifo中读数据,并将读到的内容打印到屏幕上。

向mytestfifo中写数据,fifo_w.c,代码:

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

void sys_err(const char * str)
{
	perror(str);
	exit(1);
}

int main(int argc,char *argv[])
{
	int fd,i;
	char buf[4096];
	if(argc < 2){
		printf("Enter like this:./a.out fifoname\n");
		return -1;
	}
	
	fd = open(argv[1],O_WRONLY);//打开创建的fifo文件
	if(fd < 0)
		sys_err("open");
	i=0;
	while(1){
		sprintf(buf,"hello world %d\n",i++);
		write(fd,buf,strlen(buf));//把读的内容写到FIFO文件中
		sleep(1);
	}
	close(fd);
	
	return 0;
}

 向mytestfifo中读数据,fifo_r.c,代码:

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

void sys_err(const char * str)
{
	perror(str);
	exit(1);
}

int main(int argc,char *argv[])
{
	int fd,len;
	char buf[4096];
	if(argc < 2){
		printf("./a.out fifoname\n");
		return -1;
	}
	
	fd = open(argv[1],O_RDONLY);//打开创建的fifo文件
	if(fd < 0)
		sys_err("open");
	while(1){
		len = read(fd,buf,sizeof(buf));//从FIFO文件中读数据
		write(STDOUT_FILENO,buf,len);//把读的内容写到屏幕上
		sleep(1);//多个读端时应增加睡眠秒数
	}
	close(fd);
	
	return 0;
}

结果:

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值