什么是管道

  管道是单向的、先进先出的,它把一个进程的输出和另一个进程的输入连接在一起。一个进程(写进程)在管道的尾部写入数据,另一个进程(读进程)从管道的头部读出数据

管道的分类

  管道包括无名管道名管道两种,前者用于父进程和子进程间的通信,后者可用于运行于同一系统中的任意两个进程间的通信。

 


无名管道

无名管道的创建

 

   无名管道由pipe( )函数创建:

int pipe(int filedis[2]);

 

  当一个管道被创建时,它会创建两个文件描述符:filedis[0]用于读管道,filedis[1]用于写管道。

 

关闭管道

  关闭管道只是将两个文件描述符关闭即可,可以使用普通的close函数逐个关闭。

 

无名管道读写

 

  管道用于不同进程间通信。通常先创建一个管道,再通过fork函数创建一个子进程,该子进程会继承父进程创建的管道。

  注意事项:必须在系统调用fork()前调用pipe(),否则子进程将不会继承文件描述符。,这样,就会创建两个管道,因为父子进程共享同一段代码段,都会各自调用pipe(),即建立两个管道,出现异常错误。

 

无名管道示例

 

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

相关文章: