linux中用管道實現兄弟進程通信


1 使用fork函數創建兩個子進程。在第一個子進程中發送消息到第二個子進程,第二個子進程都出來並處理。

2 在父進程中,不適用管道通信,所以什么不需要做直接關閉勒管道的兩端

3 代碼實現

 1 #include <unistd.h>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <limits.h>
 5 #include <fcntl.h>
 6 #include <sys/types.h>
 7 #define BUFSZ PIPE_BUF
 8 void err_quit(char * msg){
 9     perror( msg );
10     exit(1);
11 }
12 int main ( void ) 
13 {
14     int fd[2];
15     char buf[BUFSZ];        /* 緩沖區 */
16     pid_t pid;
17     int len = 0;
18     if ((pipe(fd)) < 0 )    /*創建管道*/
19         err_quit( "pipe" );
20     if ( (pid = fork()) < 0 )                    /*創建第一個子進程*/
21         err_quit("fork");
22     else if ( pid == 0 ){                        /*子進程中*/
23         close ( fd[0] );/*關閉不使用的文件描述符*/
24         write(fd[1], "hello son!\n", 15 );    /*發送消息*/
25         exit(0);
26     }
27     if ( (pid = fork()) < 0 )                    /*創建第二個子進程*/
28         err_quit("fork");
29     else if ( pid > 0 ){                        /*父進程中*/
30         close ( fd[0] );
31         close ( fd[1] );
32         exit ( 0 );
33     }
34     else {                                        /*子進程中*/
35         close ( fd[1] );                        /*關閉不使用的文件描述符*/
36         len = read (fd[0], buf, BUFSZ );        /*讀取消息*/
37         write(STDOUT_FILENO, buf, len);
38         exit(0);
39     }
40 }

4 截圖

 


免責聲明!

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



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