如何使用fork()命令,使您能够生成10个进程,并让它们同时执行一个小任务。
并发是一个有用的词,许多地方演示了如何在演示中只使用对fork()的一个调用。我以为您会使用某种for循环,但我试过了,在我的测试中,看起来叉()正在产生一个新的进程,做工作,然后生成一个新的进程。所以它们看起来是顺序运行的,但是如果这样做有意义的话,我怎么能同时分叉并让10个进程同时工作呢?
谢谢。
更新:感谢大家的回答,我想我一开始就误解了fork()的一些方面,但我现在明白了。干杯。
发布于 2009-09-04 19:33:20
循环调用fork():
添加代码以等待每个注释的子级:
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);发布于 2009-09-04 19:32:11
当您分出进程时,将同时运行。但是请注意,除非您有足够的可用空闲处理器,否则它们可能不会同时执行,这并不重要.
您的第二段使您看起来似乎不了解叉子是如何工作的,您必须检查返回代码以确定您是在父进程还是在分叉进程中。因此,您将让父进程运行一个循环来发送10个进程,并且在子进程中,您可以同时执行您想要做的任何事情。
发布于 2009-09-04 19:31:42
只需在“主”过程中循环一个又一个子进程,每个子进程分配一个特定的任务。
https://stackoverflow.com/questions/1381089
复制相似问题