linux c 进程 pipe 通信代码分析

本文介绍了一个使用C语言实现的管道通信示例程序。该程序通过父子进程的方式演示了如何利用管道进行进程间通信,包括创建管道、写入数据及读取数据的过程。
[root@luozhonghua 04]# cat ex04-3-pipe02.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>


int main(void){
   int result=-1;
   int fd[2],nbytes;
   pid_t pid;
   char string[]="hello,pipe";
   char readbuffer[80];


   int *write_fd = &fd[1];  //可写
   int *read_fd = &fd[0];  //read


   result = pipe(fd);  //create pipe


   if(-1 == result){
     printf("create pipe faile");
     return -1;
    }


   pid=fork(); //分叉程序


   if(-1 == pid){
    printf("fork 进程失败\n");
    return -1;
   }


   if(0 == pid ){
     close(*read_fd);
     /*向管道端写入字符*/
     result=write(*write_fd,string,strlen(string));


   }else{
     close(*write_fd);
     /* read pipe data */
     nbytes=read(*read_fd,readbuffer,sizeof(readbuffer));
     printf("接收到%d 个数据,内容:%s \n",nbytes,readbuffer);
     printf("sizeof(readbuffer) =  %d\n",sizeof(readbuffer));
   }


   return 0;

}


--------------测试结果

[root@luozhonghua 04]# ./ex04-3-pipe02
接收到10 个数据,内容:hello,pipe
sizeof(readbuffer) =  80


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luozhonghua2000

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值