【发布时间】:2012-01-01 20:55:19
【问题描述】:
好的,这是我们今天操作系统考试的练习题
在 C 中给出这个程序
#include <unistd.h>
#include <stdlib.h>
int main(){
int i;
for(i=2;i>=1&&!fork();i--)
printf("%d\n",i);
exit(EXIT_SUCCESS);
}
执行它会给出这个输出:
2
1
我发现不明确的是程序如何管理索引“i” 以及流程执行的正确顺序是什么 (如果有订单或者是调度程序建立的随机订单?)
以及为什么只打印 2 和 1 - 我的假设是:
(father executes the "for" only for i=2, prints 2 then exits ?)
(the first child starts from i=1 forks a child prints 1 exits ?)
此时我的问题是:
是否有第二个孩子没有进入 for ? 并且是 2 由父亲打印,1 由第一个孩子打印?
最后一件事:
您将如何重写此 fork-condition-for 以使其更具可读性(例如 if 语句)
【问题讨论】:
标签: c linux operating-system fork