您的位置:首页 > 运维架构 > Linux

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

2011-12-20 18:56 696 查看
#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
='\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);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐