c++ - Fork off more processes as previous finish,直到达到最大值

标签 c++ c process fork waitpid

要 fork X 个进程并让父进程等待所有进程,我有以下代码:

int maxProcesses = 10;

for (int currentChild = 0; currentChild < maxProcesses; currentChild++) {
    pid_t pid = fork();

    if (pid < 0) {
        // Error
    } else if (pid == 0) {
        // Child
    } else {
        // Parent
        // Should I call waitpid on pid and wait here instead?
    }
}

// Wait for all children
for (int currentChild = 0; currentChild < maxProcesses; currentChild++) {
    wait(NULL);
}

现在我想修改代码,以便在总共 X 个进程中,首先 fork Y,然后在它们完成时进行更多 fork ,直到达到所需的总数。我对上面的代码做了一些修改,有一些问题。

int totalProcessesToBeForked = 10;
int maxAllowedAtOnce = 5;

for (int currentChild = 0; currentChild < maxAllowedAtOnce; currentChild++) {
    forkChild(currentChild);
}

// Wait for all children
// # How do I modify this to wait for new children forked as well
// # if I move it inside parent, it will make things easier, right?
for (int currentChild = 0; currentChild < maxAllowedAtOnce; currentChild++) {
    wait(NULL);
}

void forkChild(currentChild) {
    pid_t pid = fork();

    if (pid < 0) {
        // Error
    } else if (pid == 0) {
        // Child
    } else {
        // Parent
        // # I think waiting here using waitpid will be better b/c
        // # as new forks are made, parent begins to wait for them
    }
}

我可能需要记录有多少子进程被 fork ,并将其与 totalProcessesToBeForked 进行比较,并相应地 fork 新进程。

更新代码 v1:

int maxProcesses = 10;
int maxAllowedAtOnce = 5;

int main(int argc, char* argv[]) {
    // Start timer
    alarm(10);                  // Terminate after 10s
    signal(SIGALRM, onTimeout);
    signal(SIGCHLD, catchChild);

    for (int currentChild = 0; currentChild < maxAllowedAtOnce; currentChild++) {
        forkChild(currentChild);
    }

    // # This sections runs immediately before death of any child is reported
    // # and starts cleanup processes, thus killing any/all running children

    // Completed before timeout
    endTimer = true;
    int timeRemaining = alarm(0);
    if (timeRemaining > 0) {
        printf("\nCompleted w/ %is remaining. Performing cleanup.\n", timeRemaining);

        // Kill children any running child processes, cleanup
        cleanup();
    }

    return 0;
}

void forkChild(currentChild) {
    pid_t pid = fork();

    if (pid < 0) {
        // Error
    } else if (pid == 0) {
        // Child
        execl("/bin/date", "date", 0, 0);
    } else {
        // Parent
        printf("#Log: Started %i.\n", currentChild + 1);
    }
}

void catchChild(int sig) {
    pid_t p;
    int state;
    p=wait(&state);
    printf("Got child %d\n",p);
}

void cleanup() {
    // Cleanup Code
}

示例运行:

enter image description here

编辑#2: http://ideone.com/noUs3m

最佳答案

您不想像您那样使用wait,而是想研究信号处理来处理子进程死亡。

在开始 forking 之前添加这一行

signal(SIGCHLD,catchchild);

并将此功能添加到您的代码中

void catchchild(int sig)
  {
  pid_t p;
  int state;
  p=wait(&state);
  printf("Got child %d\n",p);
  }

然后每当子进程死亡时,您的主进程将调用 catchchild

正如您已经计算出的那样,如果您知道有多少 child 被 fork 了,您可以让 catchchild 更新它,这样您的主代码就会知道 fork 一个新 child 。

要像下面这样回答你的评论,除了更多的错误检查

while(totalProcessesToBeForked)
  {
  if(currentChild < maxAllowedAtOnce)
    {
    forkChild(currentChild);
    totalProcessesToBeForked--;
    }
  sleep(1);
  }

关于c++ - Fork off more processes as previous finish,直到达到最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43084744/

相关文章:

c++ - Qt 中的错误消息和更好组织的代码

c++ - DirectX DXUT 备用 API

未捕获 c++ bad_alloc 异常

c - 为什么 C 不提供结构比较?

c - 生产者消费者信号量值不正确

c++ - 在没有分配的情况下加入并重新拆分两个 std::list

c - 如何在字符串中集成 int 变量?

iphone - iOS交叉编译!需要什么?

php - ImageMagick 多次转换同一张图片?

java - 如何知道特定功能的内存使用情况?