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!
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With