linux 进程间通信之管道和FIFO

一.管道

1.可有多个进程向一个进程写入数据,读入数据的进程只能有一个

2.管道通信只能支持单向通信,如果实现双向通信效果,则需要建立两个管道

3.管道只支持有父子关系和有共同父进程关系的子进程之间的进程通信

 int pipe(int filedes[2]);
功能:filedes 为两个元素的整型数组,pipe 调用产生一个管
道,管道的读描述符存入filedes[0],管道的写描述符存入
filedes[1]。一个进程可以向filedes[1]中写入数据,另一个进程
可以从filedes[0]中读出数据。

代码举例如下:

/*
 * piperw.c - The correct way to open a pipe and fork
 *        a child process.
 */
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <limits.h>

#define BUFSZ PIPE_BUF

void err_quit(char *msg);

int main(int argc, char *argv[])
{
	int fd[2]; /* File descriptor array for the pipe */
	int fdin; /* Descriptor for input file */
	char buf[BUFSZ];
	int pid, len;

	/* Create the pipe */
	if((pipe(fd)) < 0)
		err_quit("pipe");
    
	/* Fork and close the appropriate descriptors */
	if((pid = fork()) < 0)
		err_quit("fork");
	if (pid == 0) {
		/* Child is reader, close the write descriptor */
		close(fd[1]);
		while((len = read(fd[0], buf, BUFSZ)) > 0)
			write(STDOUT_FILENO, buf, len);
		close(fd[0]);
	} else {
		/* Parent is writer, close the read descriptor */
		close(fd[0]);
		if((fdin = open(argv[1], O_RDONLY)) < 0) {
           			perror("open");
            			/* Send something since we couldn't open the input */
            			write(fd[1], "123\n", 4);
    		} else {
        
        			while((len = read(fdin, buf, BUFSZ)) > 0)
        				write(fd[1], buf, len);
        			close(fdin);
    		}
   	 	/* Close the write descriptor */
    		close(fd[1]);
    	}
    
	waitpid(pid, NULL, 0);

	exit(EXIT_SUCCESS);
}
    
void err_quit(char *msg)
{
	perror(msg);
	exit(EXIT_FAILURE);
}

二,FIFO(命名管道)

因为以上提到的管道只支持父子进程或有相同父进程之间的子进程之间的进程通信,故而为了实现非此关系外的进程通信,FIFO油然而生,他通过一个文件写入读取实现管道通信。

/*
 * rdfifo.c - Create a FIFO and read from it
 */
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <limits.h>

int main(void)
{
	int fd;	/* Descriptor for FIFO */
	int len;     /* Bytes read from FIFO */
	char buf[PIPE_BUF];
	mode_t mode = 0666;

	if((mkfifo("fifo1", mode)) < 0) {
		perror("mkfifo");
		exit(EXIT_FAILURE);
	}

    	/* Open the FIFO read-only */
    	if((fd = open("fifo1", O_RDONLY)) < 0) {
        		perror("open");
        		exit(EXIT_FAILURE);
   	 }
    	/* Read and display the FIFO's output until EOF */
    	while((len = read(fd, buf, PIPE_BUF - 1)) > 0)
        		printf("rdfifo read: %s", buf);

    	close(fd);

    	exit(EXIT_SUCCESS);
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值