linux 进程间通信编程,有名管道的实验(存疑,为什么管道的创建在read.c里?)

代码分析

  程序分析 write.c

//fifo_write.c
//有名管道的创建与使用write部分
// mkfifo - make a FIFO special file (a named pipe)
//#include <sys/types.h>
//#include <sys/stat.h>
//int mkfifo(const char *pathname, mode_t mode);

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

#define FIFONAME	"./myfifo"
// PIPE_BUF defined in limits.h
#define BUF_SIZE	PIPE_BUF

int main(int argc, char *argv[])
{
	int fd;
	char buf[BUF_SIZE];
	int real_write;
	if (argc <=1 )
	{
		printf("Usage: %s string\n",argv[0]);
		exit(0);
	}

	sscanf(argv[1], "%s", buf);

	if ((fd = open(FIFONAME, O_WRONLY)) < 0)	//只写方式打开fifo
	{
		printf("Error open fifo files!\n");
		exit(-1);
	}
	
	//向管道中写入字符串
	if((real_write = write(fd, buf, BUF_SIZE)) > 0)
	{
		printf("Write '%s' to FIFO\n", buf);
	}
	close(fd);
	exit(0);
} 

  程序分析 read.c

//fifo_read.c
//有名管道的创建与使用read部分
// mkfifo - make a FIFO special file (a named pipe)
//#include <sys/types.h>
//#include <sys/stat.h>
//int mkfifo(const char *pathname, mode_t mode);

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

#define FIFONAME	"./myfifo"
// PIPE_BUF defined in limits.h
#define BUF_SIZE	PIPE_BUF

int main()
{
	int fd;
	char buf[BUF_SIZE];
	int real_read;

	//判断有名管道是否存在,若未创建则以相应的权限创建
	//access - check real user's permissions for a file
	//#include <unistd.h>
	//int access(const char *pathname, int mode);
	if ((access(FIFONAME, F_OK)) == -1)
	{
		if(((mkfifo(FIFONAME, 0666)) < 0) && (errno != EEXIST))
		{
			printf("Error Create FIFO file!\n");
		}
	}

	if ((fd = open(FIFONAME, O_RDONLY)) < 0)	//只读方式打开fifo
	{
		printf("Error open fifo files!\n");
		exit(-1);
	}
	
	while(1)
	{
		
		memset(buf, 0, sizeof(buf));
		//从管道中读取字符串
		
		if((real_read = read(fd, buf, BUF_SIZE)) > 0)
		{
			printf("Read '%s' from FIFO\n", buf);
			if (!strcmp(buf,"Quit")) break;
		}
	}
	close(fd);
	exit(0);
}

执行结果

  不必解释,看图
执行结果