操作系统:Linux,语言:纯C
我正在学习一般的C编程,在特殊情况下学习UNIX下的C编程。
printf()
使用fork()
调用后,我检测到该函数的奇怪行为(对我而言)。
码
#include <stdio.h>
#include <system.h>
int main()
{
int pid;
printf( "Hello, my pid is %d", getpid() );
pid = fork();
if( pid == 0 )
{
printf( "\nI was forked! :D" );
sleep( 3 );
}
else
{
waitpid( pid, NULL, 0 );
printf( "\n%d was forked!", pid );
}
return 0;
}
输出量
Hello, my pid is 1111
I was forked! :DHello, my pid is 1111
2222 was forked!
为什么第二个“ Hello”字符串出现在孩子的输出中?
是的,这恰恰是父母在开始时打印的内容,并带有父母的pid
。
但!如果我们\n
在每个字符串的末尾放置一个字符,则会得到预期的输出:
#include <stdio.h>
#include <system.h>
int main()
{
int pid;
printf( "Hello, my pid is %d\n", getpid() ); // SIC!!
pid = fork();
if( pid == 0 )
{
printf( "I was forked! :D" ); // removed the '\n', no matter
sleep( 3 );
}
else
{
waitpid( pid, NULL, 0 );
printf( "\n%d was forked!", pid );
}
return 0;
}
输出:
Hello, my pid is 1111
I was forked! :D
2222 was forked!
为什么会发生?这是正确的行为还是错误?