C fork()如何/为什么会失败
我目前正在学习C中的fork()函数。我理解它的功能(我认为)。我的问题是为什么我们要在下面的程序中检查它C fork()如何/为什么会失败,c,posix,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");
#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);
}
}
#包括
#包括
#包括
int main()
{
int-pid;
pid=fork();
如果(pid没有足够的内存来创建新进程。例如,如果内核无法分配内存,这将非常糟糕,并将导致fork()
失败
请查看此处的错误代码:
从手册页:
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.
Fork()将失败,并且在以下情况下不会创建子进程:
[EAGAIN]系统对pro的总数施加了限制-
将超过正在执行的许可证。此限制
这取决于配置。
[EAGAIN]系统对
单个服务器正在执行的进程总数
用户将被超越。
[ENOMEM]新进程的交换空间不足。
(这来自OS X手册页,但其他系统上的原因类似。)fork
可能会失败,因为你生活在现实世界中,而不是无限递归的数学幻想世界,因此资源是有限的。特别是,sizeof(pid_t)
是有限的,这就给256^sizeof(pid_t)设定了一个严格的上限在fork
可能成功的次数上(没有任何进程终止)。除此之外,您还需要担心其他资源,如内存。显然,由于以下因素,fork可能会失败(不是真正失败,而是无限挂起):
试图分析一些代码
多线程
多内存分配
另见
例如:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main()
{
size_t sz = 32*(size_t)(1024*1024*1024);
char *p = (char*)malloc(sz);
memset(p, 0, sz);
fork();
return 0;
}
运行:
如果出于某种原因,你不能在你的操作系统上创建更多的进程,它将失败。但这只是一种方式。“…因为你生活在现实世界中,而不是无限递归的数学幻想世界,因此资源是有限的。”-太好了!
gcc -pg tmp.c
./a.out