I am trying to add a parallel processing component to a single thread single process program. I am just learning some of the multi-processing methods and as such am not totally sure of their capabilities.
The program logic I am looking to implement:
- main process calls a function.
- called function fork()’s at start of a for loop.
- child continues with function work either performing other sub-functions or exiting back based on time checks.
- meanwhile, parent ends first for loop round and starts again thus re-forking a second child.
- called function fork()’s at start of a for loop.
- function continues until for loop finishes after around 10 fork()’s have been executed.
- function gets called again once completed based on a higher level timer.
Will this implementation work? Example code:
check_timer() {
for(i = 0; i < 10; i++) {
pid_t pid = fork();
if(pid == 0) {
execute child 1 checks and possible executes..
exit(); // when completed
}
else {
parent maybe does something or just ends first round of for loop..
}
}
some implementation of wait(); to wait for all children to finish before leaving check_timer() function..
}
Will this create up to 10 child processes at once executing in the background of a parent that then waits for the children to finish? Also some tips on how to use wait() would be helpful.
Yes, you will end up with 11 processes in total.
You likely want the
waitpidfunction, called until there are no more children (a return ofECHILD).EDIT: just noticed you need
pid_t pid = fork();, notpid = pid();