#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()的调用是阻塞式的调用方式。