【问题标题】:In C, how to create multiple child processes (without knowing how many u need)?在 C 中,如何创建多个子进程(不知道你需要多少)?
【发布时间】:2014-03-04 07:51:09
【问题描述】:

是否可以根据父进程中发生的情况创建多个子进程?例如,通过我父进程中的计算,我决定我需要 3 个子进程,可能是 4,5 或 6。然后最终一次将整​​数传递给子进程并从中获取退出值。有没有办法在 C 中实现这一点?

【问题讨论】:

标签: c linux process fork pipe


【解决方案1】:

类似这样的:

int childs = 5; // I want 5 childs
pid_t pid;

while (childs > 0)
  {
    if ((pid = fork()) == -1)
      return (1); // handle this error as you want
    if (pid == 0)
      break;
    childs--;
  }
// the child go there directly

您可以使用 pid_t 的数组/列表来记住所有孩子并使用 waitpid 检查他们的状态。

编辑:

以不同方式处理孩子并用数组记住它们的方法:

int childs = 5; // I want 5 childs
pid_t pid[childs];
int i;

for (i=0; i < childs; ++i) {
  if ((pid[i] = fork()) == -1)
    return (1); // handle this error as you want
  if (pid[i] == 0) {
    break;
  }
 }
switch (i) {
 case 0:
   return(function0());
   break;
 case 1:
   return(function1());
   break;
 case 2:
   return(function2());
   break;
 case 3:
   return(function3());
   break;
 case 4:
   return(function4());
   break;
 default:
   ;
 }

我不知道你到底想做什么,你也可以在条件中使用模(%)运算符来调用正确的函数。 我在那里使用 return 因为我们不想再停留在 for 循环中,'functionx()' 将完成整个新流程的工作。也可以在函数中使用。

您现在有一个 pid_t 数组,因此您可以在循环中检查孩子的状态。

【讨论】:

  • hmm.. 那么我怎样才能访问每个单独的孩子呢?假设我想在不同的孩子身上做不同的事情
  • 您无法真正“访问”它。如果您希望您的每个孩子执行特定功能,您可以简单地使用计数器,并根据该计数器的值调用不同的功能。我会用一个例子来编辑我的帖子。
猜你喜欢
  • 2017-12-26
  • 2011-09-27
  • 2014-12-13
  • 1970-01-01
  • 2012-06-25
  • 1970-01-01
  • 2011-07-02
  • 1970-01-01
  • 2017-01-20
相关资源
最近更新 更多