2013-08-03 205 views
4

请考虑以下程序。为什么shell和文件之间的输出不同

main() { 
    printf("hello\n"); 
    if(fork()==0) 
    printf("world\n"); 
    exit(0); 
} 

编译使用./a.out此程序会产生以下输出:

hello 
world 

编译使用./a.out > output此程序会产生所谓的“输出”的文件中的输出,似乎是这样的:

hello 
hello 
world 

这是为什么呢?

回答

15

因为当你输出到外壳stdout通常行缓冲,而当你写一个文件,它通常是全缓冲。

fork()后,子进程将继承缓冲区,当你输出到外壳,缓冲区是空的,因为新线\n的,但是当你输出到文件,缓冲仍然包含的内容,并会在父母和孩子的输出缓冲区中,这就是为什么hello被看到两次。

,您可以尝试这样的:

int main() { 
    printf("hello"); //Notice here without "\n" 
    if(fork()==0) 
    printf("world\n"); 
    exit(0); 
} 

你可能会看到hello两次当输出外壳为好。

3

这个答案是在俞灏的回答之后。他已经解释了很多。

main() { 
    printf("hello\n"); 
    fflush(stdout);//flush the buffer 
    if(fork()==0) 
    printf("world\n"); 
    exit(0); 
} 

然后你可以得到正确的输出。

相关问题