linux 进程通信 管道

1、 管道概述及相关API应用

1.1 管道相关的关键概念

管道是Linux支持的最初Unix IPC形式之一,具有以下特点:

  • 管道是半双工的,数据只能向一个方向流动;需要双方通信时,需要建立起两个管道;
  • 只能用于父子进程或者兄弟进程之间(具有亲缘关系的进程);
  • 单独构成一种独立的文件系统:管道对于管道两端的进程而言,就是一个文件,但它不是普通的文件,它不属于某种文件系统,而是自立门户,单独构成一种文件系统,并且只存在与内存中。
  • 数据的读出和写入:一个进程向管道中写的内容被管道另一端的进程读出。写入的内容每次都添加在管道缓冲区的末尾,并且每次都是从缓冲区的头部读出数据。

1.2管道的创建:

#include <unistd.h>
int pipe(int fd[2])

  

该函数创建的管道的两端处于一个进程中间,在实际应用中没有太大意义,因此,一个进程在由pipe()创建管道后,一般再fork一个子进程,然后通过管道实现父子进程间的通信(因此也不难推出,只要两个进程中存在亲缘关系,这里的亲缘关系指的是具有共同的祖先,都可以采用管道方式来进行通信)。

1.3管道的读写规则:

管道两端可分别用描述字fd[0]以及fd[1]来描述,需要注意的是,管道的两端是固定了任务的。即一端只能用于读,由描述字fd[0]表示,称其为管道读端;另一端则只能用于写,由描述字fd[1]来表示,称其为管道写端。如果试图从管道写端读取数据,或者向管道读端写入数据都将导致错误发生。一般文件的I/O函数都可以用于管道,如close、read、write等等。

从管道中读取数据:

  • 如果管道的写端不存在,则认为已经读到了数据的末尾,读函数返回的读出字节数为0;
  • 当管道的写端存在时,如果请求的字节数目大于PIPE_BUF,则返回管道中现有的数据字节数,如果请求的字节数目不大于PIPE_BUF,则返回管道中现有数据字节数(此时,管道中数据量小于请求的数据量);或者返回请求的字节数(此时,管道中数据量不小于请求的数据量)。注:(PIPE_BUF在include/linux/limits.h中定义,不同的内核版本可能会有所不同。Posix.1要求PIPE_BUF至少为512字节,red hat 7.2中为4096)。

关于管道的读规则验证:

/**************
 * readtest.c *
 **************/
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
main()
{
	int pipe_fd[2];
	pid_t pid;
	char r_buf[100];
	char w_buf[4];
	char* p_wbuf;
	int r_num;
	int cmd;
	
	memset(r_buf,0,sizeof(r_buf));
	memset(w_buf,0,sizeof(r_buf));
	p_wbuf=w_buf;
	if(pipe(pipe_fd)<0)
	{
		printf("pipe create error
");
		return -1;
	}
	
	if((pid=fork())==0)
	{
		printf("
");
		close(pipe_fd[1]);
		sleep(3);//确保父进程关闭写端
	      r_num=read(pipe_fd[0],r_buf,100);
          printf(	"read num is %d   the data read from the pipe is %d
",r_num,atoi(r_buf));
		
		close(pipe_fd[0]);
		exit();
	}
	else if(pid>0)
	{
	close(pipe_fd[0]);//read
	strcpy(w_buf,"111");
	if(write(pipe_fd[1],w_buf,4)!=-1)
		printf("parent write over
");
	close(pipe_fd[1]);//write
		printf("parent close fd[1] over
");
	sleep(10);
	}	
}
 /**************************************************
 * 程序输出结果:
 * parent write over
 * parent close fd[1] over
 * read num is 4   the data read from the pipe is 111
 * 附加结论:
 * 管道写端关闭后,写入的数据将一直存在,直到读出为止.
 ****************************************************/

  

向管道中写入数据:

  • 向管道中写入数据时,linux将不保证写入的原子性,管道缓冲区一有空闲区域,写进程就会试图向管道写入数据。如果读进程不读走管道缓冲区中的数据,那么写操作将一直阻塞。 
    注:只有在管道的读端存在时,向管道中写入数据才有意义。否则,向管道中写入数据的进程将收到内核传来的SIFPIPE信号,应用程序可以处理该信号,也可以忽略(默认动作则是应用程序终止)。

对管道的写规则的验证1:写端对读端存在的依赖性

#include <unistd.h>
#include <sys/types.h>
main()
{
	int pipe_fd[2];
	pid_t pid;
	char r_buf[4];
	char* w_buf;
	int writenum;
	int cmd;
	
	memset(r_buf,0,sizeof(r_buf));
	if(pipe(pipe_fd)<0)
	{
		printf("pipe create error
");
		return -1;
	}
	
	if((pid=fork())==0)
	{
		close(pipe_fd[0]);
		close(pipe_fd[1]);
		sleep(10);	
		exit();
	}
	else if(pid>0)
	{
	sleep(1);  //等待子进程完成关闭读端的操作
	close(pipe_fd[0]);//write
	w_buf="111";
	if((writenum=write(pipe_fd[1],w_buf,4))==-1)
		printf("write to pipe error
");
	else	
		printf("the bytes write to pipe is %d 
", writenum);
	
	close(pipe_fd[1]);
	}	
}

  

1.1 FIFO 命名管道

命名管道是一种特殊类型的文件,因为Linux中所有事物都是文件,它在文件系统中以文件名的形式存在。

在程序中,我们可以使用两个不同的函数调用来建立管道:

#include <sys/types.h>

#include <sys/stat.h>

int mkfifo(const char *filename, mode_t mode);

int mknode(const char *filename, mode_t mode | S_IFIFO, (dev_t) 0 );

一、实验:使用FIFO实现进程间通信

两个独立的程序:

1.      生产者程序,它在需要时创建管道,然后尽可能快地向管道中写入数据。

2.      消费者程序,它从FIFO中读取数据并丢弃它们。

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

#define FIFO_NAME "../fifoname"
#define BUFFER_SIZE PIPE_BUF
#define TEN_MEG (1024 * 5 )

int main()
{
    int pipe_fd;
    int res;
    int open_mode = O_WRONLY;
    
    int byte = 0;
    char buffer[BUFFER_SIZE + 1];
    
    if (-1 == access(FIFO_NAME, F_OK)) {
        res = mkfifo(FIFO_NAME, 0777);
        if (res != 0) {
            printf("error create fifo pipe
");
            exit(EXIT_FAILURE);
        }
    }
    
    printf("Process %d opening FIFO O_WRONLY
", getpid());
    pipe_fd = open(FIFO_NAME, open_mode);
    printf("Process %d result %d
", getpid(), pipe_fd);
    
    if (-1 != pipe_fd) {
        while (byte < TEN_MEG) {
            res = write(pipe_fd, buffer, BUFFER_SIZE);
	    printf("write to pipe %d data! and buffsize if %d
", res, BUFFER_SIZE);
            if (-1 == res) {
                printf("error write to pipe
");
                exit(EXIT_FAILURE);
            }
            
            byte += res;
        }
        
        close(pipe_fd);
    }
    else
    {
        exit(EXIT_FAILURE);
    }
    
    printf("Process %d finished
", getpid());
    
}

 消费者:

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

#define FIFO_NAME "../fifoname"
#define BUFFER_SIZE PIPE_BUF

int main()
{
    
    int pipe_fd;
    
    int open_mode = O_RDONLY;
    
    int res;
    char buffer[BUFFER_SIZE + 1];
    int byte = 0;
    
    printf("Process %d opening FIFO O_RDONLY
", getpid());
    pipe_fd = open(FIFO_NAME, open_mode);
    printf("Process %d result %d
", getpid(), pipe_fd);
    
    if (-1 != pipe_fd) {
        do
        {
            res = read(pipe_fd, buffer, BUFFER_SIZE);
	    printf("read from server %d bytes data!
", res);
            byte += res;
	    sleep(1);
        }while (res > 0);
        
        close(pipe_fd);
    }
    else
    {
        exit(EXIT_FAILURE);
    }
    
    printf("Process %d finished, %d bytes read
", getpid(), byte);
    
    
    return 0;
    
}

  

原文地址:https://www.cnblogs.com/bracken/p/3642086.html