fifo:命名管道

fifo与pipe的区别:

(1)有inode

(2)不相关的进程也能通过fifo交换数据

fifo实例代码(步骤):

(1)在shell中使用mkfifo创建程序中将要用到的FIFO管道(创建fifo类型的文件)

         $mkfifo –m 666 fifo1

(2)vi write_fifo.c

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include

int main(void)
{
	int fd;
	int n,i;
	char buf[PIPE_BUF];
	time_t tp;
	printf("I am %d\n",getpid());
	if((fd=open("fifo1",O_WRONLY))<0)
	{
		perror("open error");
		exit(1);
	}

	for(i=0;i<10;i++)
	{
		n=sprintf(buf,"write_fifo %d sends %ld",getpid(),time(&tp));	
		printf("Send msg:%s\n",buf);
		if((write(fd,buf,n+1))<0) 
		{
			perror("write");
			close(fd);
			exit(1);
		}
		sleep(3);
	}
	close(fd);
	exit(0);

}

(3)vi read_fifo.c

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
int main(void)
{
	int fd;
	int len;
	char buf[PIPE_BUF];
	mode_t mode = 0666; /* FIFO文件的权限 */
	if((fd=open("fifo1",O_RDONLY))<0) /* 打开FIFO文件 */
	{
		perror("open");
		exit(1);
	}
	while((len=read(fd,buf, PIPE_BUF))>0) /* 开始进行通信 */
		printf("read_fifo read: %s\n",buf);
	close(fd); /* 关闭FIFO文件 */
	exit(0);
}

(4)在shell中分别编译上述两个程序如下:

$gcc write_fifo.c–o write_fifo

$gcc read_fifo.c–o read_fifo

(5)打开两个shell分别运行程序write_fifo 和程序 read_fifo

fifo:命名管道_第1张图片fifo:命名管道_第2张图片

你可能感兴趣的:(Linux)