我正在学习函数system()是stdlib.h并意识到我可以创建一个使用system()运行自己的程序。我写了这段代码并试了一下:
#include <stdio.h>
#include <stdlib.h>
int main(){
printf("x");
system("./a.out");
}
每次运行时,它都会正常打印563 x,然后才能正常退出(无错误)。我想知道是什么阻止了程序以及这个数字的来源,因为它对我来说似乎很随意。感谢
感谢您对第一个程序的见解,但我不相信系统正在停止它,因为资源耗尽的原因如下:我刚刚编写了这个新程序,但它还没有停止。 / p>
#include <stdio.h>
#include <stdlib.h>
int main(){
printf("x");
system("./a.out");
system("./a.out");
}
此外,当我尝试打开一个新的控制台窗口时出现此错误:
/.oh-my-zsh/lib/theme-and-appearance.zsh:24: fork failed: resource temporarily unavailable
/.oh-my-zsh/oh-my-zsh.sh:57: fork failed: resource temporarily unavailable
答案 0 :(得分:31)
我将首先处理第二个程序,因为这是最容易解释的。请尝试使用此代码,它将打印出递归深度。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv){
int depth = argc > 1 ? atoi(argv[1]) : 0;
printf("%d\n", depth);
char cmd[128];
sprintf(cmd, "%s %d", "./a.out", depth+1);
system(cmd);
system(cmd);
}
它会一直长到你的极限(在我的情况下是538),然后开始在递归树上上下乱。
530 531 532 533 534 535 536 537 538 538 537 538 538 536 537
最终这个过程会结束,但需要很长时间!
至于第一个节目。我相信您只是遇到了用户进程限制。
您可以通过运行
找到您的流程限制ulimit -u
在我的情况下,限制是709.计算我的其他进程运行
ps aux | grep user | wc -l
这给了我171. 171 + 538(程序死亡的深度)给你一个可靠的答案:)
答案 1 :(得分:5)
程序中没有任何内容可以阻止无限递归。
You execute a.out.
a.out executes a.out
a.out executes a.out
a.out executes a.out
a.out executes a.out
等等。
在某些时候,系统运行资源并且不执行下一个system
调用,程序以相反的顺序退出。您的计算机似乎在运行程序563次时达到了限制。
答案 2 :(得分:3)
要了解幕后发生的情况,请使用以下程序之一:
这些程序列出了进程发出的所有系统调用,包括任何错误代码。
阅读他们的文档,因为从长远来看,这比我在这里给出一个用例更有帮助。