4
votes

So I'm working on a program that will do a certain task multiple times. I've written the program once already using threads, but now I'm required to do it using processes with fork().

With threads, I'd simply create the specified number of threads, have them execute a function (changing a variable in shared memory), and then finally execute something that used the final value in shared memory.

Now however I want to do the same thing but I'm not sure how to do it as everytime I call fork() it essentially doubles itself. So obviously if I call fork() in a forloop, each parent and child process will then go through the loop calling fork() on their own.

So my question in a nutshell: how could I create an exact number of child processes using fork (lets say I need 5 children), and have my parent process wait until these 5 are done executing before it moves on?

Thanks for the help!

2
Each child knows that it is the child; make sure it only does the things a child is supposed to do (go to school?) and make sure it exits without continuing where the parent process is executing (at work?). As with the answer by niculare, or Quentin.Jonathan Leffler

2 Answers

8
votes

I think this will work:

int processes = 5;
int i;
for (i = 0; i < processes; ++i) {
    if (fork() == 0) {
        // do the job specific to the child process
        ...
        // don't forget to exit from the child
        exit(0);
    }
}
// wait all child processes
int status;
for (i = 0; i < processes; ++i)
    wait(&status);
1
votes

Either you can structure your processes so that each one forks a relevant number of children (for example, the parent will fork n times, the children n-1, their children n-2, etc.), or you would limit the forks so that only the parent keep on the loop (that would be the simplest case). So make the children exit the loop.