【Linux线程通信】有名管道(FIFO)——阻塞读写

多线程间使用有名管道通信

创建有名管道,如果管道存在则直接使用

//创建有名管道,如果管道存在则直接使用
	int n = mkfifo("./myfifo",0664);
	if( n < 0 && errno!=EEXIST)
	{
		perror("mkfifo");
		return -1;
	}

负责管道写数据线程

void *thread_fun_write(void *p)
{
	char *buf = "12345";
	int fd;
	fd = open("./myfifo",O_WRONLY);
	if(fd == -1)
	{
		printf("write fifo open fail....\n");
		exit(-1);
		return;
	}
	while(1)
	{
		write( fd, buf, strlen(buf)+1 );
		puts("write ok");
		sleep(5);
	}
	close(fd);
}

负责读取管道内容的线程,如果管道内没有数据,阻塞等待读取数据。

void *thread_fun_read(void *p)
{

	int fd;

	fd = open("./myfifo", O_RDONLY );
	if(fd == -1)
	{
		printf("read fifo open fail...\n");			
		exit(-1);
		return;
	}
	char buf[100] = {0};
	int num;//保存读数据大小
	while(1)
	{
		num = read( fd, buf, 100 );
		puts("read ok:");
		puts(buf);
	}
	close(fd);
}

完整代码如下:

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

void *thread_fun_write(void *p)
{
	char *buf = "12345";
	int fd;
	fd = open("./myfifo",O_WRONLY);
	if(fd == -1)
	{
		printf("write fifo open fail....\n");
		exit(-1);
		return;
	}
	while(1)
	{
		write( fd, buf, strlen(buf)+1 );
		puts("write ok");
		sleep(5);
	}
	close(fd);

}
void *thread_fun_read(void *p)
{

	int fd;

	fd = open("./myfifo", O_RDONLY );
	if(fd == -1)
	{
		printf("read fifo open fail...\n");			
		exit(-1);
		return;
	}
	char buf[100] = {0};
	int num;//保存读取数据的大小
	while(1)
	{
		num = read( fd, buf, 100 );
		puts("read ok:");
		puts(buf);
	}
	close(fd);
}
int main()
{
	//创建有名管道,如果管道存在则直接使用
	int n = mkfifo("./myfifo",0664);
	if( n < 0 && errno!=EEXIST)
	{
		perror("mkfifo");
		return -1;
	}
	//创建线程
	pthread_t writeId,readId;
	pthread_create( &writeId, NULL, thread_fun_write, NULL );
	pthread_create( &readId, NULL, thread_fun_read, NULL);

	pthread_join(writeId,NULL);
	pthread_join(readId,NULL);
	while(1);
	return 0;
}

若想实现写进程阻塞,读进程非阻塞。
只需将读进程中管道打开方式改为

fd=open("./myfifo",O_RDONLY | O_NONBLOCK)

先运行写进程(被阻塞),再运行读进程,程序一切正常。
先运行读进程,程序直接崩掉(Segmentation fault (core dumped))。

你可能感兴趣的:(Linux学习)