2014-09-21 61 views
0

這裏是輸出---叉問題 - 執行fork()的叉前,命令後也跑兩次

家長:我的PID爲4525 家長:我父母的PID爲3350 parant started- 4525 3350 叉 之前在叉 兒童4526 4525 在父 ---家長結束---

當我嘗試執行下面的代碼---

void main(int argc, char *argv[]) 
{ 
    int status; 
    pid_t my_pid, parent_pid,child_pid; 

    my_pid = getpid(); 
    parent_pid = getppid(); 
    printf("\nParent: my pid is %d", my_pid); 
    printf("\nParent: my parent's pid is %d", parent_pid); 
    printf("\nparant started- %d %d",my_pid,parent_pid); 
    printf("\nBefore Fork"); 

    if((child_pid = fork()) < 0) 
    { 
     perror("fork failure"); 
     exit(1); 
    } 

    if(child_pid == 0) 
    { 
     printf("\n Child %d %d\n",getpid(),getppid()); 

    } 
    else 
    { 
     printf("\nIn parent"); 
     wait(&status); 
     printf("\n---Parent End---\n"); 
    } 

} 

爲什麼前叉正在打印兩次?謝謝

+0

...和'main()的返回''int',順便說一句。 – 2014-09-21 05:12:44

回答

4

這是因爲你沒有沖洗輸出緩衝區之前fork()。更改爲:

printf("\nBefore Fork\n"); 

或:

printf("\nBefore Fork"); 
fflush(stdout); 
+0

It worked !! ...謝謝 – gargsajal9 2014-09-21 05:18:08