1

I want to write a program in C using fork method to compute n factorial. this program (process) creates only one child. Each of the processes (parent and child) will compute approximately half of the complete sequence. Then the parent combines the results and print the final result.

  • I've got an idea which is to divide the numbers between 1 to n into two intervals [1,n/2], [n/2,n] and assign the job of each interval to a process but i'm not so familiar with fork.

How can I pass data between the two processes?

Adrian Panasiuk
  • 7,249
  • 5
  • 33
  • 54
Ibrahim.I
  • 229
  • 1
  • 4
  • 18
  • 1
    So, your question is that you'd like someone to explain `fork()`? or... what exactly? – Mike Jun 04 '13 at 17:28
  • @Mike I wan't some piece of code that does the job. I kinda know the algorithm in general (I've put the idea) but I'm not aware of how to use fork in C and how to pass the partial result from the child to the parent. – Ibrahim.I Jun 04 '13 at 17:32
  • http://stackoverflow.com/questions/12430461/how-to-use-fork-in-an-if-statement Does this help? – Adrian Panasiuk Jun 04 '13 at 17:46
  • @AdrianPanasiuk I know what `fork()` does but I just want to know how to program `fork()` in C with passing data from child to parent and vice versa. – Ibrahim.I Jun 04 '13 at 17:56
  • @Ibrahim.I I see, in that case I'll add the missing piece of the question into the post – Adrian Panasiuk Jun 04 '13 at 18:26

1 Answers1

1

Don't use fork, but rather use pthreads. Its easier when combining the results (rather than having to deal with IPC because you forked).

KrisSodroski
  • 2,796
  • 3
  • 24
  • 39
  • that's the requirements :( using fork once. – Ibrahim.I Jun 04 '13 at 17:44
  • That's not too terrible. Just use a pipe to store your results, and have the first child start at the middle and the parent start at the end (until the middle). Then store your info in a pipe, and have your parent read it, and multiply its results by the result in the pipe. Make sure you lock the file from the parent in the child process! – KrisSodroski Jun 04 '13 at 17:48