如何/为什么可以fork()失败 [英] How/Why can fork() fail
本文介绍了如何/为什么可以fork()失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前就读于C.叉()函数,我理解它做什么(我认为)。我的问题是,为什么我们在下面的程序检查吗?
I'm currently studying the fork() function in C. I understand what it does (I think). My question is why do we check it in the following program?
#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);
}
}
在这个程序中,我们检查PID返回为&lt; 0,这将指示失败。为什么可以fork()失败?
In this program we check if the PID returned is < 0, which would indicate a failure. Why can fork() fail?
推荐答案
从手册页:
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.
(这是从OS X的手册页,但在其它系统上的原因是相似的。)
(This is from the OS X man page, but the reasons on other systems are similar.)
这篇关于如何/为什么可以fork()失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文