linux中用無名管道進行文件的讀寫


1管道是什么:

  水管子大家知道,有兩端,在此一端用來讀一端用來寫,其中一端的輸出作為另外一端的輸入。

2 函數原型

  int pipe(int pipefd[2]);//參數中分別代表的兩端

3 例子:管道一端作為寫 另外一端作為讀 父子進程實現

 1 #include <unistd.h>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 
 5 int main()
 6 {
 7     pid_t pid;
 8     int temp;
 9     int pipedes[2];
10     char s[14]="letgo";
11     char d[14];
12     if((pipe(pipedes))==-1)
13     {
14         perror("pipe");
15         exit(EXIT_FAILURE);
16     }
17     
18     if((pid=fork())==-1)
19     {
20         perror("fork error");
21         exit(EXIT_FAILURE);
22     }else if(pid==0)
23     {
24         //printf(“子進程寫數據到管道讀端”);
25         printf("子進程寫數據到管道讀端\n");
26         if((write(pipedes[1],s,14))==-1)
27         {
28             perror("write");
29             exit(EXIT_FAILURE);
30         }else
31         {
32             printf("所寫入得數據是%s\n",s);
33             exit(EXIT_SUCCESS);
34         }
35     }else if(pid>0)
36     {
37         sleep(2);//等待子進程結束
38         printf("父進程從管道讀數據\n");
39         if((read(pipedes[0],d,14))==-1)
40         {
41             perror("read");
42             exit(EXIT_FAILURE);
43         }
44         printf("從管道讀端讀出得數據是%s\n",d);
45     }
46     
47     return 1;
48 }

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM