【问题标题】:How to run child processes simultaneously? in c如何同时运行子进程?在 c
【发布时间】:2015-10-09 20:25:35
【问题描述】:

所以这是我的代码,它将一个 int 作为命令行参数,然后派生 N 个子进程(同时运行)。然后当每个孩子结束时,父母会回显该孩子退出状态。

但现在我只能一个一个地做,但不能同时做。我该怎么做?

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <time.h>

int main ( int argc, char *argv[] )
{
    int i, pid, ran;

    for(i = 0; i < atoi(argv[1]); i++) {
    pid = fork();
    srand(time(NULL));
    ran = (rand() % 10) + 1 ;

     if (pid < 0) {
        printf("Error");
        exit(1);
     } else if (pid == 0) {
        printf("Child (%d): %d\n", i + 1, getpid());
        printf("Sleep for = %d\n", ran);
        sleep(ran);
        exit(ran); 
     } else  {
        int status = 0;
        pid_t childpid = wait(&status);
        printf("Parent knows child %d is finished. \n", (int)childpid);
     }
  }

}

【问题讨论】:

  • 函数:srand() 应该只被调用一次,而不是每次都通过循环
  • 在使用argv[1]之前,代码需要将argc与2进行比较以确保argv[1]参数存在,如果argc
  • 代码编译不干净。它缺少#include &lt;sys/wait.h&gt;#include &lt;unistd.h&gt; 在编译时始终启用所有警告(对于gcc,至少使用:-Wall -Wextra -pedantic
  • 请一致地缩进代码。这使得我们人类更容易阅读/理解

标签: c fork


【解决方案1】:

您在生成孩子的循环内调用 wait(),因此在当前孩子完成之前,它不会继续循环以启动下一个孩子。

您需要在单独的循环中在循环外调用wait()

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <time.h>

int main ( int argc, char *argv[] )
{
    int i, pid, ran;

    for(i = 0; i < atoi(argv[1]); i++) {
        pid = fork();
        srand(time(NULL));
        ran = (rand() % 10) + 1 ;

         if (pid < 0) {
            printf("Error");
            exit(1);
         } else if (pid == 0) {
            printf("Child (%d): %d\n", i + 1, getpid());
            printf("Sleep for = %d\n", ran);
            sleep(ran);
            exit(ran); 
         }
    }

    for(i = 0; i < atoi(argv[1]); i++) {
        int status = 0;
        pid_t childpid = wait(&status);
        printf("Parent knows child %d is finished. \n", (int)childpid);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 2013-05-12
    • 2011-10-11
    相关资源
    最近更新 更多