gpt4 book ai didi

c - 万无一失的 fork ?

转载 作者:太空狗 更新时间:2023-10-29 15:24:18 24 4
gpt4 key购买 nike

我的 C 类包含实现一个非常小的 shell。

我们的 shell 检查用户的输入行是否有内部命令(例如 cd 或 exit),如果没有找到,它会 forks() 和 execs() 输入行。

我希望实现一个万无一失的 fork (这超出了本类(class)的职责范围,请不要让我做自己的功课,这更多是为了了解更多 linux 而进行的个人研究'内部)。我目前的做法是:

t = fork();             
if (t < 0) {
if (errno == ENOSYS) {
printf("fork() is not supported on this platform. Minishell will not work.");
break;
}
else if (errno == ENOMEM) {
printf("No free kernel memory. Minishell will exit.");
break;
}
else {
int try = 0;
while (t < 0 && try < 10) {
try++;
t = fork();
}
}
continue;
}

我的理解是 ENOSYS 不允许 fork ,因此我们退出,ENOMEM 表示内核内存问题 - 超过我的工资等级(我没有得到报酬,我是学生 ;)),因此我们也退出。保持 EAGAIN 有两种形式,这两种形式都可以通过等待并再次调用 fork() 来解决。

在之前的练习中,我们发起了 10000 次 fork ,如果我没记错的话,大约有 1500 次失败,直到我们实现了一个像我上面的 while 那样的计数器。如果我想以一种不那么天真的方式实现这个东西,我该如何进行?我想,特别是硬编码的十次尝试有点愚蠢。

谢谢。

最佳答案

我认为您当前的重试方法误解了 fork 的 EAGAIN 错误的含义。来自 Linux 手册页:

EAGAIN fork() cannot allocate sufficient memory to copy the parent's page tables and allocate a task structure for the child.

EAGAIN It was not possible to create a new process because the caller's RLIMIT_NPROC resource limit was encountered. To exceed this limit, the process must have either the CAP_SYS_ADMIN or the CAP_SYS_RESOURCE capability.

第一个几乎等同于 ENOMEM,第二个是达到进程上限的问题。除非您希望您的 minishell 一直让子进程死亡,否则快速连续尝试 10 次可能什么也做不了。

我还建议让 EAGAIN 成为您的 fork 代码的 fatal error 。

但是,如果您的程序可以做一些事情来减轻内存压力(释放您的程序缓存等),您可以这样做并再试一次。

值得一提的是,在正常负载下,任何现代系统几乎都不存在导致 fork 失败的条件。

关于c - 万无一失的 fork ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19862505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com