linuxC多进程通讯---fifo

特点

•FIFO文件,有文件名字
–可以像普通文件一样存储在文件系统之中
–可以像普通文件一样使用open/read/write读写
–跟PIPE一样,属于流式文件,不能使用lseek定位
•具有写入原子性、可同时对FIFO进行写操作,如日志系统/var/log
•First In First Out:最先被写入FIFO的数据,最先被读出来
–默认阻塞读、阻塞写的特性,可以在open的时候进行设置
–当一个进程打开FIFO的一端时,如果另一端没有打开,该进程会被阻塞

fifo与pipe区别

–联系
•在内核中的实现:fs/pipe.c,本质上都是内存中的一块page cache
•通过向内核注册pipefs来实现,可以通过I/O接口read、write等访问
–区别
•匿名管道pipe通过自己的两端读写描述符进行读写操作
•命名管道有自己的文件名,可以通过文件名直接进行读写操作
•匿名管道pipe一般用于亲缘进程间通信
•命名管道FIFO可用于非亲缘进程间通信

举例(父子进程)

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

int main (void)
{
	mkfifo ("my_fifo", 0644);
	int ret_from_fork;
	int fifo_fd;
	ret_from_fork = fork ();
	if (ret_from_fork == -1)
	{
		perror ("fork");
		exit (EXIT_FAILURE);
	}
	else if (ret_from_fork == 0)
	{
		fifo_fd = open ("my_fifo", O_WRONLY);
		char buf[100];
		memset (buf, 0, 100);
		printf ("child process(%d) input msg:", getpid ());
		fgets (buf, 100, stdin);
		int write_len = write (fifo_fd, buf, strlen (buf));
		printf ("%d bytes hace been sent\n", write_len);
		_exit (EXIT_SUCCESS);
	}
	else
	{
		sleep (1);
		fifo_fd = open ("my_fifo", O_RDONLY);
		char buf[100];
		memset (buf, 0, 100);
		read (fifo_fd, buf, 100);
		printf ("parent process(%d) read msg from FIFO: %s\n", getpid (), buf);
		exit (EXIT_SUCCESS);
	}
	return 0;
}

举例(不相关进程)

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

int main (int argc, char *argv[])
{
	mkfifo ("my_fifo", 0644);

	int fifo_fd = open ("my_fifo", O_RDONLY);

	char buf[100];
	memset (buf, 0, 100);
	read (fifo_fd, buf, 100);
	printf ("Read from FIFO: %s\n", buf);

	return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

int main (int argc, char *argv[])
{
	mkfifo ("my_fifo", 0644);
	int fifo_fd = open ("my_fifo", O_WRONLY);
	char buf[100];
	memset (buf, 0, 100);

	fgets (buf, 100, stdin);
	int write_len = write (fifo_fd, buf, strlen (buf));
	printf ("%d bytes have been sended to FIFO.\n", write_len);
	return 0;
}
发布了349 篇原创文章 · 获赞 6 · 访问量 9753

猜你喜欢

转载自blog.csdn.net/qq_23929673/article/details/99815160