Bro*_*olf 6 c unix concurrency command-line multiprocessing
如何使用fork()命令,以便产生10个进程并让它们同时执行一个小任务.
并发是一个有效的词,许多显示如何使用fork的地方只在他们的演示中使用一个fork()调用.我以为你会使用某种for循环,但我尝试过,在我的测试中,fork()似乎产生了一个新进程,正在做工作,然后产生一个新进程.所以它们似乎是按顺序运行但是如果有意义的话,我如何同时进行分叉并让10个进程同时进行工作?
谢谢.
更新:谢谢你的回答,我想我最初误解了fork()的一些方面,但我现在明白了.干杯.
Ken*_*nan 15
呼叫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);
| 归档时间: | 
 | 
| 查看次数: | 15024 次 | 
| 最近记录: |