2016-11-04 132 views
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

2源代码是相同? – Danh

+0

它是一个索引的东西。当我说'printf(“%d”,i ++);'它会应用'我',然后增加它。另一个会增加'i',然后添加'printf'。因此,如果'int i = 0',第一种情况会打印0(但在下次引用它时增加它),但第二种情况会打印1(因为它给自己加1,然后调用' printf'函数) – Fallenreaper

+0

相同的代码如何产生不同的结果?也许你正在做一些你没有展示的东西。还要确保父进程没有被杀死 – smac89

回答

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*****将从未打印

相关问题