linux中用管道實現父子進程通信


1 用戶要實現父進程到子進程的數據通道,可以在父進程關閉管道讀出一端,

然后相應的子進程關閉管道的輸入端。

2 先用pipe()建立管道 然后fork函數創建子進程。父進程向子進程發消息,子進程讀消息。

3 實現

 1 #include <unistd.h>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <fcntl.h>
 5 #include <limits.h>
 6 #include <sys/types.h>
 7 #define BUFSZ PIPE_BUF  /*PIPE_BUF管道默認一次性讀寫的數據長度*/
 8 int main ( void ) 
 9 {
10     int fd[2];
11     char buf[BUFSZ];
12     pid_t pid;
13     ssize_t len;
14     if ( (pipe(fd)) < 0 ){                        /*創建管道*/
15         perror ( "failed to pipe" );
16         exit( 1 );
17     }
18     if ( (pid = fork()) < 0 ){                    /* 創建一個子進程 */
19         perror ( "failed to fork " );
20         exit( 1 );
21     }
22     else if ( pid > 0 ){
23         close ( fd[0] );                        /*父進程中關閉管道的讀出端*/
24         write (fd[1], "hello tian chaoooo!\n", 20 );    /*父進程向管道寫入數據*/
25         exit (0);
26     }
27     else {
28         close ( fd[1] );                        /*子進程關閉管道的寫入端*/
29         len = read (fd[0], buf, BUFSZ );        /*子進程從管道中讀出數據*/
30         if ( len < 0 ){
31             perror ( "process failed when read a pipe " );
32             exit( 1 );
33         }
34         else
35             write(STDOUT_FILENO, buf, len);    /*輸出到標准輸出*/
36         exit(0);
37     }
38 }

4 截圖

 


免責聲明!

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



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