问题描述
如何在这样你可以生成10个进程,并让他们做一个小任务并行的方式使用fork()的命令。
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.
并发是最关键的词,很多地方显示如何使用fork只使用()在他们的演示一个调用叉。我以为你会用某种形式的for循环,但我想,它似乎在我的测试,该叉()'s的产卵一个新的进程,做的工作,然后生成一个新的进程。因此,他们似乎正在运行顺序,但我怎么能同时叉,并有10个进程同时做的工作如果是有道理的?
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?
感谢。
更新:的答案家伙谢谢,我想我只是误会叉的某些方面()开始,但我现在明白了吧。干杯。
Update: Thanks for the answers guys, I think I just misunderstood some aspects of fork() initially but i understand it now. Cheers.
推荐答案
呼叫叉()
在一个循环:
添加code等待每个孩子的意见:
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()的并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!