多个 fork() 并发 [英] Multiple fork() Concurrency
问题描述
How do you use the fork() command in such a way that you can spawn 10 processes and have them do a small task concurrently.
Concurrent is the operative word, many places that show how to use fork only use one call to fork() in their demos. I thought you would use some kind of for loop but i tried and it seems in my tests that the fork()'s are spawning a new process, doing work, then spawning a new process. So they appear to be running sequentially but how can I fork concurrently and have 10 processes do the work simultaneously if that makes sense?
Thanks.
Update: Thanks for the answers guys, I think I just misunderstood some aspects of fork() initially but i understand it now. Cheers.
Call fork()
in a loop:
Adding code to wait for children per comments:
int numberOfChildren = 10;
pid_t *childPids = NULL;
pid_t p;
/* Allocate array of child PIDs: error handling omitted for brevity */
childPids = malloc(numberOfChildren * sizeof(pid_t));
/* Start up children */
for (int ii = 0; ii < numberOfChildren; ++ii) {
if ((p = fork()) == 0) {
// Child process: do your work here
exit(0);
}
else {
childPids[ii] = p;
}
}
/* Wait for children to exit */
int stillWaiting;
do {
stillWaiting = 0;
for (int ii = 0; ii < numberOfChildren; ++ii) {
if (childPids[ii] > 0) {
if (waitpid(childPids[ii], NULL, WNOHANG) != 0) {
/* Child is done */
childPids[ii] = 0;
}
else {
/* Still waiting on this child */
stillWaiting = 1;
}
}
/* Give up timeslice and prevent hard loop: this may not work on all flavors of Unix */
sleep(0);
}
} while (stillWaiting);
/* Cleanup */
free(childPids);
这篇关于多个 fork() 并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!