命名管道的创建和使用

命名管道(FIFO)和无名管道基本相同,但也有不同点:无名管道只能由父子进程使用;但是通过命名管道,不相关的进程也能交换数据。


#include <sys/types.h>
#include <sys/stat.h>
 
int mkfifo(const char *pathname, mode_t mode);
 
pathname: FIFO文件名
mode:属性(同文件操作)
 
一旦创建了一个FIFO,就可用open打开它,一般的文件访问函数(close、read、write等)都可用于FIFO。


当打开FIFO时,非阻塞标识(O_NONBLOCK)将对以后的读写产生影响:
1、没有使用O_NONBLOCK:访问要求无法满足时进程将阻塞。如果试图读取空的FIFO,将导致进程阻塞。
2、使用O_NONBLOCK:访问要求无法满足时不阻塞,立刻出错返回。errno是ENXIO。


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


//创建命名管道
int main()
{
	int ret = mkfifo("/home/mkfifo", 0777);
	if (ret == -1)
	{
		perror ("mkfifo");
		return -1;
	}
		
	return 0;
}


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

#define SIZE 1024


//从终端输入,并将输入写入管道
int main()
{
	int fd = open("/home/mkfifo", O_WRONLY);
	if (fd== -1)
	{
		perror ("mkfifo");
		return -1;
	}
	
	char buf[SIZE];
	while (1)
	{
		fgets (buf, SIZE, stdin);
		
		write (fd, buf, strlen(buf));
	}
		
	return 0;
}


#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#define SIZE 1024


//从管道内读数据
int main()
{
	int fd = open("/home/mkfifo", O_RDWR);
	if (fd == -1)
	{
		perror ("mkfifo");
		return -1;
	}
	
	char buf[SIZE];
	while (1)
	{
		int ret = read (fd, buf, SIZE);
		buf[ret] = '\0';
		
		printf ("读到 %d 字节: %s\n", ret, buf);
	}
		
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值