我在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
``` ```
看起来只有子进程正在运行!
答案 0 :(得分:3)
我认为您的第二个代码示例是:
int main(void){
int pid;
int i = 0;
pid = fork();
if(pid != 0){
while(1)
i++;
printf("a%d\n",i);
}
else{
while(1){
printf("b%d\n",i++);
}
}
}
与
相当int main(void){
int pid;
int i = 0;
pid = fork();
if(pid != 0){
while(1) {
i++;
}
// Unreachable code
// vvvvvvvvvvvvvvvvvvv
printf("a%d\n",i);
}
else{
while(1){
printf("b%d\n",i++);
}
}
}
因此,永远不会打印a*****