歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux下的無名管道pipe的設計

Linux下的無名管道pipe的設計

日期:2017/3/1 9:47:05   编辑:Linux編程

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 數組地址不合法。

示例:

[email protected]:/home/linuxidc/桌面/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
[email protected]:/home/linuxidc/桌面/c++# g++ pipe_test.cpp -o pipe_test
[email protected]:/home/linuxidc/桌面/c++# ./pipe_test
parent write1 Hello!
parent write2 Pipe!

10 numbers read from the pipe is Hello Pipe
[email protected]:/home/linuxidc/桌面/c++#

無名管道的創建是在fork創建前,通過pipe()創建管道,然後通過fork創建子進程,之後,子進程會拷貝父進程的代碼段/數據段及堆棧段,因此,創建的管道會被復制一份,子進程一份,父進程一份,為了使管道正常通訊,必須處理已有管道。

Copyright © Linux教程網 All Rights Reserved