关于Linux fork的问题
我目前正在学习操作系统,我有这段代码,但我收到无限循环的递归调用,我想要的只是创建一些儿子的并计算斐波那契(数字很小),我不明白为什么儿子可以根本没有完成,提前感谢:
int fibonaci(int n) {
if(n < 2){
return n;
}
return fibonaci(n - 1) + fibonaci(n - 2);
}
int main(int argc, char* argv[]) {
//some checkings, and variables
for (i = 0; i < argc; ++i) {
son_pid = fork();
if (son_pid == 0) {
fibonaci(var); //var is some finite variable
break;
}
}
if(son_pid != 0){
while(wait(&status) != -1){}
}
return 0;
}
编辑
完成所有检查,问题出在逻辑上!
I'm currently learning operating systems, I have this snippet of the code but I receive infinite loop of recursive calls, all I want is to create some son's and to calculate fibonacci(with small numbers), I can't understand why sons can't finish at all, thanks in advance:
int fibonaci(int n) {
if(n < 2){
return n;
}
return fibonaci(n - 1) + fibonaci(n - 2);
}
int main(int argc, char* argv[]) {
//some checkings, and variables
for (i = 0; i < argc; ++i) {
son_pid = fork();
if (son_pid == 0) {
fibonaci(var); //var is some finite variable
break;
}
}
if(son_pid != 0){
while(wait(&status) != -1){}
}
return 0;
}
edited
all checkings were done, problem is with logic!!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可能不是解决方案,但尝试用 return 0 代替break;
我确实相信问题在于分叉/处理子代码与父代码。我不明白你为什么把休息时间放在那里。计算完斐波那契数之后,儿子应该回来了。休息可能会产生一些意想不到的结果。
This may not be the solution, but try to put a return 0 instead of the break;
I do believe that the problem is in the forking/treating son vs parent code. I can't see why you put the break there. After calculating the fibonacci, the son should return. The break may be having some unwanted results.
wait()
的“默认行为” 是返回如果它没有可以被杀死的子项,则立即使用-1
,如您所料:和
我的快速测试证实该程序有效。但是,
wait()
行为可能存在一些变化。好的一面是,您知道您
fork()
有多少个孩子(argc
许多)。因此,wait()
循环的一个可以说更正确的版本是:我希望这会有所帮助。
The "default behavior" of
wait()
is to return immediately with-1
if it has no children that can be killed, as you expected:and
My quick test confirms that the program works. However, there could be some variation in
wait()
behavior.On the bright side, you know how many children you
fork()
'd (argc
many). Therefore, an arguably more correct version of thewait()
loop is:I hope this helps.