我必须创建一个管道,然后创建一个fork,并允许父进程和子进程(1子进程)通信。
特别是Parent从文件读取并在管道上写入文件的内容(应该是巨大的)然后子必须从管道读取并在stdout上显示文件的内容。
gcc编译器没问题,但是当我运行可执行文件时没有任何反应。
有人可以帮我处理我的代码吗?我哪里出错了,为什么?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define size 80
int main(int argc,char*argv[]){
if(argc!=2){
write(2,"Missing parameters on the command line\n",38);
return 1;
}
int fd[2];
pid_t pid;
int fd_in;
int i;
char buf[size];
//create pipe for communication between parent and child in this case parent read the file at size bytes at time write into pipe then child write data on stdout received from father
if(pipe(fd)!=0){
printf("Pipe failure\n");
return 1;
}
pid=fork();
if(pid<0){
printf("Fork() failure\n");
return 1;
}
if(pid>0){ // parent process
close(fd[0]);// parent write into pipe ,close reading
if(access(argv[1],F_OK)!=0){
write(2,"Input file does not exists\n",35);
return 1;
}
if(fd_in=open(argv[1],O_RDONLY)<0){
printf("Cannot open for reading file %s\n",argv[1]);
return 1;
}
while(read(fd_in,buf,size)>0){
write(fd[1],buf,size);
}
close(fd[1]); // close write into pipe
wait(0);
}
if(pid==0){ //Child process
close(fd[1]);// child read from pipe, close writing
while(read(fd[0],buf,size)>0){
write(1,buf,size);
}
close(fd[0]);// close reading
return 0;
}
close(fd_in);
return 0;
}