2
我學習叉()在Linux和兩個程序具有不同的執行結果似乎完全一樣的對我說:printf(「%d」,i ++)和i ++之間有什麼區別;的printf( 「%d」,i)的?
第一個具有「正常」的結果,父母和孩子peocesses交替運行:
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源代碼是相同? – Danh
它是一個索引的東西。當我說'printf(「%d」,i ++);'它會應用'我',然後增加它。另一個會增加'i',然後添加'printf'。因此,如果'int i = 0',第一種情況會打印0(但在下次引用它時增加它),但第二種情況會打印1(因爲它給自己加1,然後調用' printf'函數) – Fallenreaper
相同的代碼如何產生不同的結果?也許你正在做一些你沒有展示的東西。還要確保父進程沒有被殺死 – smac89