Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fork() an exact number of children

Tags:

c

fork

children

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!

like image 669
pledgehollywood Avatar asked Jan 13 '23 23:01

pledgehollywood


1 Answers

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);
like image 150
niculare Avatar answered Jan 25 '23 09:01

niculare