Multiple child process

前端 未结 4 1525
死守一世寂寞
死守一世寂寞 2020-12-01 01:59

can someone help me about how to create multiple child processes which have the same parent in order to do \"some\" part of particular job?

for example, an external

4条回答
  •  臣服心动
    2020-12-01 02:18

    Here is how to fork 10 children and wait for them to finish:

    pid_t pids[10];
    int i;
    int n = 10;
    
    /* Start children. */
    for (i = 0; i < n; ++i) {
      if ((pids[i] = fork()) < 0) {
        perror("fork");
        abort();
      } else if (pids[i] == 0) {
        DoWorkInChild();
        exit(0);
      }
    }
    
    /* Wait for children to exit. */
    int status;
    pid_t pid;
    while (n > 0) {
      pid = wait(&status);
      printf("Child with PID %ld exited with status 0x%x.\n", (long)pid, status);
      --n;  // TODO(pts): Remove pid from the pids array.
    }
    

提交回复
热议问题