#include "unpipc.h"
#include <iostream>
#include <myerror.h>
using namespace std;
void client(int,int),server(int,int);
int main(int argc,char **argv)
{
int pipe1[2],pipe2[2];
pid_t childpid;
pipe(pipe1); //创建管道
pipe(pipe2);
if((childpid=fork())==0) //子进程,做服务器
{
close(pipe1[1]); //关闭管道1的写入
close(pipe2[0]); //关闭管道2的读出
server(pipe1[0],pipe2[1]);
exit(0); //终止子进程
}
close(pipe1[0]);
close(pipe2[1]);
client(pipe2[0],pipe1[1]);
waitpid(childpid,NULL,0); //等待子程序结束
exit(0);
}
void client(int readfd,int writefd)
{
size_t len;
ssize_t n;
char buff[MAXLINE];
cout<<"enter the file name please:";
fgets(buff,MAXLINE,stdin);
len=strlen(buff);
if(buff[len-1]=='\n')
len--;
write(writefd,buff,len);
while((n=read(readfd,buff,MAXLINE))>0)
write(STDOUT_FILENO,buff,n);
}
void server(int readfd,int writefd)
{
int fd;
ssize_t n;
char buff[MAXLINE];
if((n=read(readfd,buff,MAXLINE))==0)
err_quit("end-of-file while reading pathname");
buff[n]='\0';
if((fd=open(buff,O_RDONLY))<0)
{
snprintf(buff+n,sizeof(buff)-n, ": can't open, %s\n",strerror(errno));
n=strlen(buff);
write(writefd,buff,n);
}
else
{
while((n=read(fd,buff,MAXLINE))>0)
write(writefd,buff,n);
close(fd);
}
}