Hello,
after reading many tutorials on how to start a new process using fork() I'm still having some dificulty understanding it. What I would like to achieve is, for my own understanding, a simple code that starts two DIFFERENT calculations as separate processes at the SAME time and then when both are finished, a third calculation adds computed values of both processes. It is very important that both processes start at the same time and run in parallel to each other and if, for example, one of both processes finishes first, it STILL waits for second process to finish and then both processes are terminated and values from their calculations are added together. I was thinking of something like this:
Code:
a=1+1 ..this is computed in one process
b=2+2 ..this is computed in second process which runs PARALLEL to the first one
and is started as separate process at the SAME time as the first process
..then, after both processes are finished:
c=a+b ..the value of c must then be ofcourse 6. Also, if for example process
a=1+1 finishes first (or does so process b=2+2), it waits for the other to
finish so they also terminate at the same time before c=a+b is
calculated.
..now the code I tried is:
Code:
#include <stdio.h>
#include <unistd.h>
int main()
{
int pid;
float a, b, c;
pid = fork();
if (pid == 0)
a=1+1;
else wait();
b=2+2;
c=a+b;
printf("c=%f\n", c);
return 0;
}
..and the output I got is:
Code:
c=6.000000
c=4.000000
Now I'm not sure if this is correct? It does display c=6 but then also c=4..
Did both processes start at the same time in the above code (did they run in parallel)?? Can someone confirm this, or better, can maby someone who has good understanding of fork-join processes post the minimal lenght code which would be CORRECT solution for the given problem at the beginning?
Also, is it possible to start more than two processes at once - let's say that for the above problem there is a third calculation d=3+3, so that we would have 3 processes running at the same time and when they are finished, c is computed as c=a+b+d ? What would the code look like for 3 parallel processes?
Thank you for any suggestions and help
regards
c.