-1

I'm writting in c a program that the father ask the user to insert the number to calculate the factorial of a number. That number is calculated in factorial.c

So i guess what i need to do is:

-Father ask a number to the user:

-Factorial.c read the number and calculate the number

-Factorial.c write the number calculated

-Do a dup2 to redirect the output

      // 2 Pipe and Fork created
      if(x == 0){ //Father

       close(p1[0]);
       write(p1[1],&number_by_keybord, BUFFER);
       close(p1[1]);
       close(p[1]);     

       dup2(p[0],0);  //Read the number returned by factorial.c
       read(p[0], &num_factorial,BUFFER);
       printf("Pipe: factorial %d\n", num_factorial);           
       close(p[0]);                 
       wait(NULL);

  }else{        
    execlp("./factorial", "factorial", NULL);
    perror("Exec error\n");
   }    

And now the factorial.c

   void main(){
       read(0,&num,sizeof(int));

       //Number calculated

      write(1,&result,sizeof(int));
     return 0;
     }

But when i execute the program freezes or just put a random number calculating

There is any problema with the dup2? i guess to retrive the correct result i have to do the dup2( , 0) and in factorial i need a read and a write

Thank you!

Joseph
  • 129
  • 2
  • 3
  • 12
  • What is the question? I do not see any question here. Questions end with a Question Mark (***?***) – abelenky Apr 01 '16 at 15:35
  • 1
    You have not presented enough code to duplicate the problem. – John Bollinger Apr 01 '16 at 15:43
  • The rest the code its just the a method to create pipes and forks, ask a number to the user (number_by_keybord) and a for to calculate the factorial in the factorial.c ... Perhaps i need more code to use the dup and to get the result of factorial.c ... but i guess i dont need. Sugestion? – Joseph Apr 01 '16 at 15:48

1 Answers1

0

Hard to guess because you do not show enough to duplicate your problem, but there seem to be a problem in this code: in child (fork returns 0 to child and child pid to parent) you correctly write to a pipe, and read from other pipe, but in the other process you fail to redirect the pipes to 0 an 1 file descriptors. You should write:

...
}else{
    dup2(p1[0], 0);
    dup2(p[1], 1);
    execlp("./factorial", "factorial", NULL);
    perror("Exec error\n");
}
Serge Ballesta
  • 121,548
  • 10
  • 94
  • 199