日期:2014-05-16  浏览次数:20678 次

Linux下的无名管道pipe的设计

1. 函数说明

pipe(建立管道):
1) 头文件 #include<unistd.h>
2) 定义函数: int pipe(int filedes[2]);
3) 函数说明: pipe()会建立管道,并将文件描述词由参数filedes数组返回。
              filedes[0]为管道里的读取端
              filedes[1]则为管道的写入端。
4) 返回值:  若成功则返回零,否则返回-1,错误原因存于errno中。

    错误代码:
         EMFILE 进程已用完文件描述词最大量
         ENFILE 系统已无文件描述词可用。
         EFAULT 参数 filedes 数组地址不合法。


示例:


root@wl-MS-7673:/home/wl/桌面/c++# cat -n pipe_test.cpp 
     1	
     2	#include <unistd.h>
     3	#include <sys/types.h>
     4	#include <errno.h>
     5	#include <stdio.h>
     6	#include <string.h>
     7	#include <stdlib.h>
     8	#include <sys/wait.h>
     9	/*
    10	 * 程序入口
    11	 * */
    12	int main()
    13	{
    14		int pipe_fd[2];
    15		pid_t pid;
    16		char buf_r[100];
    17		char* p_wbuf;
    18		int r_num;
    19		
    20		memset(buf_r,0,sizeof(buf_r));
    21		
    22		/*创建管道*/
    23		if(pipe(pipe_fd)<0)
    24		{
    25			printf("pipe create error\n");
    26			return -1;
    27		}
    28		
    29		/*创建子进程*/
    30		if((pid=fork())==0)  //子进程执行序列
    31		{
    32			printf("\n");
    33			close(pipe_fd[1]);//子进程先关闭了管道的写端
    34			sleep(2); /*让父进程先运行,这样父进程先写子进程才有内容读*/
    35			if((r_num=read(pipe_fd[0],buf_r,100))>0)
    36			{
    37				printf("%d numbers read from the pipe is %s\n",r_num,buf_r);
    38			}	
    39			close(pipe_fd[0]);
    40			exit(0);
    41	  	}
    42		else if(pid>0) //父进程执行序列
    43		{
    44			close(pipe_fd[0]); //父进程先关闭了管道的读端
    45			if(write(pipe_fd[1],"Hello",5)!=-1)
    46				printf("parent write1 Hello!\n");
    47			if(write(pipe_fd[1]," Pipe",5)!=-1)
    48				printf("parent write2 Pipe!\n");
    49			close(pipe_fd[1]);
    50			wait(NULL); /*等待子进程结束*/
    51			exit(0);
    52		}
    53		return 0;
    54	}
    55	
    56	
root@wl-MS-7673:/home/wl/桌面/c++# g++ pipe_test.cpp -o pipe_test
root@wl-MS-7673:/home/wl/桌面/c++# ./pipe_test 
parent write1 Hello!
parent write2 Pipe!

10 numbers read from the pipe is Hello Pipe
root@wl-MS-7673:/home/wl/桌面/c++# 

无名管道的创建是在fork创建前,通过pipe()创建管道,然后通过fork创建子进程,之后,子进程会拷贝父进程的代码段/数据段及堆栈段,因此,创建的管道会被复制一份,子进程一份,父进程一份,为了使管道正常通讯,必须处理已有管道。