Linux下父进程通过管道发送文件名给子进程,子进程获取文件名后首先判断文件是否存在,不存在,通过管道返回错误信息,存在,将文件内容返回给父进程

#include <unistd.h>
#include <string.h>
#include <stdio.h>
void pro_client(int rfd,int wfd){
char str[]="file.dat";
int n;
char buf[100];
n=strlen(str);
write(wfd,str,n);
read(rfd,buf,100);
printf("parent process:%s\n",buf);
}
void pro_server(int rfd,int wfd){
int n,fd;
char buf[1024];
n=read(rfd,buf,1024);
buf[n]='\0';
if((fd=open(buf,0))<0){
strcat(buf,"can't open.\n");
write(wfd,buf,strlen(buf));
}
else{
while((n=read(fd,buf,1024))>0)
write(wfd,buf,n);
}
}

void main(){
int pipe1[2];
int pipe2[2];
int pid;
pipe(pipe1);
pipe(pipe2);
pid=fork();
if(pid){
close(pipe1[0]);
close(pipe2[1]);
pro_client(pipe2[0],pipe1[1]);
while(wait()!=pid);
close(pipe1[1]);
close(pipe2[0]);
}
else{
close(pipe1[1]);
close(pipe2[0]);
pro_server(pipe1[0],pipe2[1]);
close(pipe1[0]);
close(pipe2[1]);
}
exit(0);
}


你可能感兴趣的:(linux,server,include)