2014-09-21 51 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