Wait() 运行两次?

Wait() runs twice?

在我下面的代码中,我运行宁一个 parent 进程,它分叉成两个 child 进程。在 child(getpid()); 之后,两个 children 都以一个状态退出。

然而,当我 运行 parent 进程时,它总是以某种方式决定 运行 parent 部分两次(设置两个不同的 pid 值),并且我只是不能一次达到 运行。有没有办法在得到一个值后让等待停止?

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

void child(int n) { //n: child pid
  printf("\nPID of child: %i \n", n);

  //random number rand
  int randFile = open("/dev/random", O_RDONLY);
  int r;

  if(rand < 0)
    printf("ERROR: %s\n", strerror(errno));
  else {
    unsigned int seed;
    read(randFile, &seed, 4); //&rand is a pointer, 4 bytes
    int randClose = close(randFile);

    srand(seed); //seeds rand() with random from /dev/random
    r = rand();

    if(randClose < 0)
      printf("ERROR: %s\n", strerror(errno));

    //range between 5 and 20 seconds
    r = r % 20;
    if( r < 5)
      r = 5;
  }
  //  printf("\n%i\n", r);
  sleep(r);
  //  sleep(1);
  printf("\n child with pid %i FINISHED\n", n);

  exit( r );
}

int main() {
  printf("\nPREFORK\n");

  int parentPID = getpid();

  int child0 = fork();
  if(child0 < 0)
    printf("ERROR: %s\n", strerror(errno));

  int child1 = fork();
  if(child1 < 0)
    printf("\nERROR: %s\n", strerror(errno));

  if(getpid() == parentPID)
    printf("\nPOSTFORK\n");

  //if children
  if(child1 == 0) //using child1 as child-testing value b/c when child1 is set, both children are already forked
    child(getpid());

  int status;
  int pid = wait(&status);

  //parent
  if(getpid() != 0) {
    if( pid < 0)
      printf("\nERROR: %s\n", strerror(errno));
    if ( pid > 0 && pid != parentPID) {
      printf("\nPID of FINISHED CHILD: %i\n Asleep for %i seconds\n", pid, WEXITSTATUS(status));
      printf("PARENT ENDED. PROGRAM TERMINATING");
    }
  }
  return 0;
}

parent正在做:

int child0 = fork();  // + test if fork failed
int child1 = fork();  // + test if fork failed

首先你只有parent。 在第一个分叉之后,你有 parent 和第一个 child,两者都 在相同的执行点 ,所以就在下一个分叉之前。 所以在那之后 parent re-creates 一个 child,第一个 child 创建它自己的 child (并且会像 parent 一样) .

您必须使用 if/else 以确保 child 不会分叉。即:

child0 = fork();  // add check for errors
if (child0 == 0) {
  // the 1st child just have to call that
  child(getpid());
  exit(0);
}
// here we are the parent
child1 = fork();
if (child1 == 0) {
  // the 2nd child just have to call that
  child(getpid());
  exit(0);
}

当然,您可以采用不同的方式,这只是一个示例。要点是不要在 child.

中调用 fork()