你如何使用fork()命令来产生10个进程,让他们同时执行一个小任务。
并发是一个可操作的词,许多显示如何使用fork的地方只在其演示中使用fork()的一个调用。 我以为你会使用某种循环,但我试过,似乎在我的testing中,叉()的产卵一个新的进程,做工作,然后产卵一个新的进程。 所以他们似乎是顺序运行,但我怎么能同时叉,并有10个进程同时工作,如果这是有道理的?
谢谢。
更新:谢谢你们的答案,我想我刚刚误解了fork()的一些方面,但是现在我明白了。 干杯。
在循环中调用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);
当你分离进程时,将会同时运行。 但是请注意,除非有足够的可用空闲处理器,否则它们可能实际上并不是同时执行,这应该不是真正的问题。
你的第二段看起来好像不理解fork是如何工作的,你必须检查返回代码,看看你是在父进程还是在fork进程中。 所以你可以让父母运行一个循环来分离10个进程,而在你的孩子中你可以做任何你想做的事情。
只是循环在产生一个又一个孩子的“主”过程中,每一个都分配一个特定的任务。
你也可能想看看POSIX线程(或pthreads)。 这里是一个教程: