【问题标题】:Run child processes in parallel with fork与 fork 并行运行子进程
【发布时间】:2013-11-24 07:33:47
【问题描述】:

我需要创建“n”个子进程,它们必须随机休眠几秒,并且父进程必须在任何子进程完成时通知。问题是每个子进程一个接一个地运行,我需要它们并行工作。 (在代码中我只是创建了 3 个孩子。)

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>

int main(void)
{
 pid_t pid;
 int x,zeit,status,w,n=0;

 for(x=1;x<=3;x++)
 {
 pid=fork();  
    n++;
    srand(time(NULL));
  if(pid)
  {

    w=wait(&status);

   printf("Process %d finished in %d seconds (Dad:%d cuenta %d)\n",w,WEXITSTATUS(status),getppid(),n);

  }
  else
  {
   int n;
   zeit=rand()%3+1;
   sleep(zeit);
   exit(zeit);

  }

 }
exit(0);
 return 0;
}

【问题讨论】:

    标签: process fork parent-child wait


    【解决方案1】:

    在开始下一个过程之前,您明确地等待每个过程完成

    for(x=1;x<=3;x++)
    {
      pid=fork();  
      n++;
      srand(time(NULL));
      if(pid)
      {  
        w=wait(&status);    
        printf("Process %d finished in %d seconds (Dad:%d cuenta %d)\n",
               w, WEXITSTATUS(status), getppid(), n);
        ...
      }
    

    如果您希望它们并行运行,则必须创建 3 个不同的进程,并在等待其中任何一个完成之前启动它们。

    【讨论】:

      猜你喜欢
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 2014-07-12
      • 1970-01-01
      • 2016-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多