linux 管道 (双向管道流模型)

#include<unistd.h>
#include<stdio.h>
void WriteG(int fd,char *str,int len)// 写入固定长度报文
{
char buf[255];
memset(buf,0,sizeof(buf));
sprintf(buf,"%s",str);
write(fd,buf,len);
}
char *ReadG(int fd,int len)
{
//读取固定长度的报文
char buf[255];
memset(buf,0,sizeof(buf));
read(fd,buf,len);
return(buf);
}
void WriteC(int fd,char *str)
{
//显示长度输入操作
char buf[255];
sprintf(buf,"%04d%s",strlen(str),str);
write(fd,buf,strlen(buf));
}
char *ReadC(int fd)
{//显示长度的输出操作
char buf[255];
int i,j;
memset(buf,0,sizeof(buf));
j=read(fd,buf,4);//读入长度域数据
i=atoi(buf);//转化长度域为整形
j=read(fd,buf,i);//读入后续报文
return(buf);
}
void main()
{
int fildes1[2],fildes2[2];
pid_t pid;
char buf[255];
if(pipe(fildes1)<0||pipe(fildes2)<0)
{
   fprintf(stderr,"pipe error/n");
return;
}
if((pid=fork())<0)
{
fprintf(stderr,"fork error/n");
return;
}

if(pid==0)
{
close(fildes1[1]);
close(fildes2[0]);
strcpy(buf,ReadG(fildes1[0],10));//读取管道数据
fprintf(stderr,"[child] buf=[%s]/n",buf);
WriteC(fildes2[1],buf);
strcpy(buf,ReadG(fildes1[0],10));//读取管道数据
fprintf(stderr,"[child] buf=[%s]/n",buf);
WriteC(fildes2[1],buf);
return;
}
//父进程
close(fildes1[0]);
close(fildes2[1]);
WriteG(fildes1[1],"hell0!",10);
WriteG(fildes1[1],"world!",10);
fprintf(stderr,"[father] buf=[%s]/n",ReadC(fildes2[0]));
fprintf(stderr,"[father] buf=[%s]/n",ReadC(fildes2[0]));
}


          结果截图:

 

问题:

 结果怎么会有乱码呢?程序本身有错?还是。。。。。?

pipe()的调用是阻塞式的调用方式。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值