天天看点

IPC - FIFO

FIFO(有时也被称为有名管道,命名管道)使用方式与管道(PIPE)类似,可参考:http://blog.csdn.net/u010275850/article/details/45867621

最大的区别就是FIFO可用于任意两个进程间通信。FIFO是一种文件类型,因此对于FIFO的操作类似于文件操作,如读、写、打开等操作。

当open一个fifo时,非阻塞标志(O_NONBLOCK)会产生如下影响:

1、一般情况下(没有指定O_NONBLOCK),只读open要阻塞到某个其他进程为写而打开这个FIFO为止。类似的,只写open要阻塞到某个其他进程为读而打开它为止。

2、如果指定了O_NONBLOCK,则只读open立即返回。但是,如果没有进程为读而打开一个fifo,那么只写open将返回-1,并将errno设置成ENXIO。

示例如下:

read进程:

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

void main()
{
	int fd;
	char buf[7];
//	if(0==mkfifo("/home/fzz/lesson23_NamedPipe/fifo",0666))
//		printf("Creat Success!\n");
	fd=open("/home/fzz/lesson23_NamedPipe/fifo",O_RDONLY);
	if(read(fd,buf,7)==7)
			printf("Read is %s\n",buf);
	close(fd);
	unlink("/home/fzz/lesson23_NamedPipe/fifo");
}
           

write进程:

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

void main()
{
	int fd;
	char *buf="Hello!";
	if(0==mkfifo("/home/fzz/lesson23_NamedPipe/fifo",0666))
		printf("Creat Success!\n");
	fd=open("/home/fzz/lesson23_NamedPipe/fifo",O_WRONLY);
	if(write(fd,buf,7)==7)
			printf("Write Success!\n");
	close(fd);
	
}
           

参考书籍《Unix环境高级编程(第三版)》

继续阅读