我正在使用exec,管道和叉子编写程序
我的主程序创建管道,叉子。父亲通过键盘询问一个号码,然后将其发送到另一个名为" Factorial" (儿子用exec)。 fatorial接收数字,计算fatorial并将结果发送回主程序......但结果总是-1。
主程序
int pipeFromProgram[2], pipeToProgram[2],numero_keyboard= 0, num_factorial=-1
// Forks and Pipes ..
pipeFromProgram = createPipe();;
pipeToProgram = createPipe();
x = createSon();
if(x == 0) { //Father
numero_teclado = escolherNumero();
close(pipeToProgram[0]);
write(pipeToProgram[1],&numero_teclado, BUFFER); //The other program receives correctly the number.
close(pipeToProgram[1]);
close(pipeFromProgram[1]);
read(pipeFromProgram[0], &num_factorial,BUFFER); //Receive the result
printf("PIPE %d\n",num_factorial); //The result its always -1 (declared as)
close(pipeFromProgram[0]);
wait(NULL);
}else{
close(pipeToProgram[1]);
dup2(pipeToProgram[0], 0);
dup2(pipeFromProgram[1],1);
close(pipeToProgram[0]);
execlp("./factorial", "factorial", NULL);
perror("Exec error\n");
}
Fatorial.c
int main(void){
int i , result = 1, num = 1;
read(0,&num,sizeof(int));
printf("Numero recebido %d\n\n", num); //Number its correct
for (i = 1; i <= num; i++){
result = result * i; //Factorial ...
}
write(1,&result,sizeof(int)); //also tried the &result+1
return 0;
}
这是输出的例子: 要计算的数量:4
1
2
6
24 /So fatorial.c receive the number correctly and calculate it
PIPE: -1
正如你可以看到结果总是-1(声明的值)..所以我猜这个问题是它写在fatorial中。我错了吗?
void cratePipe(int p[2]){
int i;
if(pipe(p) == -1){
perror("Pipe failed");
}
}
由于