我如何才能使进程彼此并行创建而不是一个接一个地创建?

How do I make it so that processes are created parallel to each other rather than one after another?

我需要帮助修改这段代码。现在,它创建一个进程,然后等待它的终止。之后,创建另一个进程,然后等待其终止。我想对其进行修改,使其同时创建两个进程并并行执行它们。代码是:

#include <sys/types.h>
#include <stdio.h>
int main(int argc, char * argv[]) {
  pid_t pid;
  int status;
  pid = fork();
  if (pid != 0) {
    while (pid != wait( & status));
  } else {
    sleep(5);
    exit(5);
  }
  pid = fork();
  if (pid != 0) {
    while (pid != wait( & status));
  } else {
    sleep(1);
    exit(1);
  }
}

这是应该完成这项工作的代码:

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

int main(void)
{
  pid_t pid = fork();
  if (pid != 0)
    printf("Child 1 PID = %d\n", pid);
  else
  {
    sleep(5);
    exit(5);
  }
  pid = fork();
  if (pid != 0)
  {
    printf("Child 2 PID = %d\n", pid);
    int corpse;
    int status;
    while ((corpse = wait(&status)) > 0)
        printf("Child %d exited with status 0x%.4X\n", corpse, status);
  }
  else
  {
    sleep(1);
    exit(1);
  }
  return 0;
}

有一次我 运行 它,我得到了输出:

Child 1 PID = 49582
Child 2 PID = 49583
Child 49583 exited with status 0x0100
Child 49582 exited with status 0x0500

如果您愿意,可以将 wait() 循环及其变量声明移到 if 结构之后,紧接在末尾的 return 0; 之前。那会给你更好的对称性。您甚至可以将子创建阶段包装到一个调用两次的函数中:

static void procreate(int kidnum, int naptime)
{
    int pid = fork();
    if (pid != 0)
        printf("Child %d PID = %d (nap time = %d)\n", kidnum, pid, naptime);
    else
    {
        sleep(naptime);
        exit(naptime);
    }
}

然后在 main() 中,您只需两次调用 procreate() 和等待循环:

int main(void)
{
    procreate(1, 5);
    procreate(2, 1);

    int corpse;
    int status;
    while ((corpse = wait(&status)) > 0)
        printf("Child PID %d exited with status 0x%.4X\n", corpse, status);
    return 0;
}