fork()如何/为什么会失败

Jui*_*icy 9 c posix

我正在研究C中的fork()函数.我理解它的作用(我认为).我的问题是为什么我们在以下程序中检查它?

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
  int pid;
  pid=fork();

  if(pid<0)/* why is this here? */
  {
    fprintf(stderr, "Fork failed");
    exit(-1);
  }
  else if (pid == 0)
  {
    printf("Printed from the child process\n");
  }
  else
  {
    printf("Printed from the parent process\n");
    wait(pid);
  }
}
Run Code Online (Sandbox Code Playgroud)

在这个程序中,我们检查返回的PID是否<0,这表示失败.为什么fork()会失败?

Ark*_*kku 19

从手册页:

 Fork() will fail and no child process will be created if:
 [EAGAIN]           The system-imposed limit on the total number of pro-
                    cesses under execution would be exceeded.  This limit
                    is configuration-dependent.

 [EAGAIN]           The system-imposed limit MAXUPRC (<sys/param.h>) on the
                    total number of processes under execution by a single
                    user would be exceeded.

 [ENOMEM]           There is insufficient swap space for the new process.
Run Code Online (Sandbox Code Playgroud)

(这是来自OS X手册页,但其他系统的原因相似.)


R..*_*R.. 13

fork可能会因为你生活在现实世界中而失败,而不是一些无限递归的数学幻想之地,因此资源是有限的.特别是,它sizeof(pid_t)是有限的,并且这使得256 ^ sizeof(pid_t)的硬上限fork可能成功的次数(没有任何进程终止).除此之外,您还有其他资源需要担心内存.

  • "......因为你生活在现实世界中,而不是一些无限递归的数学幻想世界,因此资源是有限的." - 太好了! (9认同)

non*_*ame 2

可能没有足够的内存来创建新进程。