linux fifo 有名管道

有名管道可以实现互不关联的进程间的通信


1、创建有名管道

mkfifo

int mkfifo(const char *filename,mode_t mode) 

filename:要创建的管道 

mode:

O_RDONLY:读管道 

O_WRONLY:写管道 

O_RDWR:读写管道 

O_NONBLOCK:非阻塞 

O_CREAT:如果该文件不存在,那么就创建一个新的文件,并用第三的参数为其设置权限 

O_EXCL:如果使用 O_CREAT 时文件存在,那么可返回错误消息。这一参数可测试文件是否存在 

返回值:成功返回0,出错返回-1

测试代码:

#include <sys/types.h> 
#include <sys/stat.h> 
#include <errno.h> 
#include <fcntl.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#define FIFO "/tmp/testfifo"

main(int argc,char** argv) 
{
	char buf[100]; 
	pid_t pid;
	memset(buf,0,sizeof(buf)); 
	/*创建有名管道,并设置相应的权限*/ 
      if((mkfifo(FIFO,O_CREAT|O_EXCL)<0)&&(errno!=EEXIST)) 
            printf("cannot create fifoserver\n"); 
	if((pid = fork()) == 0)
	{
		/*子进程读*/
		int fd;
		fd = open(FIFO,O_RDONLY);
		if(fd < 0)
		{
			printf("open error\n");
			exit(-1);
		}
		while(1)
		{
			read(fd, buf, sizeof(buf));
			printf("read	:%s\n",buf);
			sleep(1);
		}
		close(fd);
	}
	else if(pid > 0)
	{
		/*父进程写*/
		int fd;
		fd = open(FIFO,O_WRONLY);
		if(fd < 0)
		{
			printf("open error\n");
			exit(-1);
		}
		while(1)
		{

			printf("please input strings\n");
			fgets(buf, sizeof(buf), stdin);
			write(fd, buf, strlen(buf));
			printf("write	:%s\n",buf);
			sleep(1);
		}
		close(fd);
	}
	else
	{
		printf("fork error\n");
		exit(-1);
	}
	unlink(FIFO); 
	return 0;

}

输出结果:

please input strings
helloworld
read	:helloworld

write	:helloworld

please input strings


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值