这是一项学术活动。我应该从父进程读取一个整数,将它发送给子进程,并且该子进程应该调用factorial的exec函数(必须从stdin读取并在stdout上写入)。父亲必须显示exec函数的结果。
显然,exec函数只读取了我做过的stdin重定向的垃圾(随机大值)。无法弄清楚原因。
这是主程序和exec函数(factorial)的代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define MAX_BUFFER 80
int main (){
int pipeFatherChild[2], pipeChildFather[2],i;
pid_t pid;
if(pipe(pipeFatherChild)==-1 || pipe(pipeChildFather)==-1){
perror("pipe Error!");
return -1;
}
pid = fork();
if(pid<0){
perror("fork Error!");
return -1;
}
if(pid>0){//father
int value;
char result[MAX_BUFFER];
close(pipeFatherChild[0]);
close(pipeChildFather[1]);
printf("Please insert nunber to calculate factorial:\n");
scanf("%d",&value);
write(pipeFatherChild[1],&value,sizeof(int));
close(pipeFatherChild[1]);
wait(NULL);//wait for child
int ret;
while((ret=read(pipeChildFather[0],&result,MAX_BUFFER)!=0)){
printf("PAI DIZ: %s\n", result);
}
close(pipeChildFather[0]);
}else{//child
close(pipeFatherChild[1]);
dup2(pipeFatherChild[0],0);
close(pipeFatherChild[0]);
close(pipeChildFather[0]);
dup2(pipeChildFather[1],1);
close(pipeChildFather[1]);
execl("./factorial", "factorial");
perror("Child Error\n");
}
return 0;
}
因子计划:
#include <stdio.h>
int factorial(int n){
if(n==0)
return 1;
return n * factorial(n-1);
}
int main(){
int n;
fscanf(stdin,"%d", &n);
fprintf(stdout,"Factorial of %d is %d\n", n, factorial(n));
return 0;
}