【发布时间】:2016-11-04 03:54:09
【问题描述】:
我在Linux中学习fork(),两个执行结果不同的程序在我看来完全一样:
第一个具有“正常”结果,父子进程交替运行:
6 int main(void){
7 int pid;
8 int i = 0;
9 pid = fork();
10 if(pid != 0){
11 while(1)
12 printf("a%d\n",i++);
13 }
14
15 else{
16 while(1){
17 printf("b%d\n",i++);
18 }
19 }
20 }
$./test1.out
``` ```
b670071
a656327
b670072
a656328
b670073
a656329
b670074
a656330
b670075
a656331
b670076
a656332
b670077
a656333
b670078
a656334
b670079
a656335
b670080
a656336
b670081
```
然而,第二个却有完全不同的结果:
4 int main(void){
5 int pid;
6 int i=0;
7 pid = fork();
8 if(pid != 0){
9 while(1)
10 i++;
11 printf("a%d\n",i);
12
13 }
14
15 else{
16 while(1){
17 i++;
18 printf("b%d\n",i);
19 }
20 }
21 }
$./test2.out
``` ```
b811302
b811303
b811304
b811305
b811306
b811307
b811308
b811309
b811310
b811311
b811312
b811313
b811314
b811315
b811316
b811317
b811318
b811319
b811320
b811321
b811322
b811323
b811324
b811325
b811326
b811327
b811328
b811329
b811330
``` ```
看起来只有子进程在运行!
【问题讨论】:
-
2源代码相同吗?
-
它是一个索引的东西。当我说
printf("%d", i++);时,它会应用i,然后增加它。另一个将增加i,然后添加doprintf。所以如果int i = 0,第一种情况会打印0(但在下一次引用时递增),但第二种情况会打印1(因为它给自己加1,然后会调用printf函数) -
相同的代码怎么可能产生不同的结果?也许你正在做一些你没有表现出来的事情。还要确保父进程没有在某处被杀死
-
@Fallenreaper 如果在这些声明之前有一个
while(1),那就不一样了。 -
您错过了第二个程序中第 9 行的 while 循环中的 {}。看起来像复制+粘贴或编辑错误,因为您在第一个程序的循环中也没有括号,尽管在那里没有区别。 PS 感谢您对代码进行行编号;难得的享受。