linux进程间通信之有名管道

时间:2021-08-08 15:13:39

linux进程间通信之有名管道生产者进程

/*************************************************************************
	> File Name: named_pipe_w.c
	> Author: XXDK
	> Email: v.manstein@qq.com 
	> Created Time: Thu 16 Mar 2017 10:51:22 PM PDT
 ************************************************************************/

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

int main()
{
	int ret;
	int fd;

	if((ret = mkfifo("./fifo", 0666)) != 0) {
		if(errno == EEXIST) {
			puts("fifo exist\n");
		}else {
			perror("make fifo error");
		}
	}
	
	// 阻塞在此处等待另一端的写打开
	fd = open("./fifo", O_WRONLY);

	write(fd, "xxdk", 4);
	printf("write data ok\n");
	
	exit(0);

}

linux进程间通信之有名管道消费者进程

/*************************************************************************
	> File Name: named_pipe_r.c
	> Author: XXDK
	> Email: v.manstein@qq.com 
	> Created Time: Thu 16 Mar 2017 10:51:22 PM PDT
 ************************************************************************/

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

int main()
{
	int ret;
	int fd;
	char buf[10] = {0};

	if((ret = mkfifo("./fifo", 0666)) != 0) {
		if(errno == EEXIST) {
			puts("fifo exist\n");
		}else {
			perror("make fifo error");
		}
	}
	fd = open("./fifo", O_RDONLY);

	read(fd, buf, 4);
	printf("read data ok: %s\n", buf);

	exit(0);

}