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 截图

 

转载于:https://www.cnblogs.com/lanjianhappy/p/7222527.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值