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

 

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值