“fork()”之后的printf异常操作系统: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 1111I was forked! :DHello, my pid is 11112222 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 1111I was forked! :D2222 was forked!为什么会发生这种事?它是正确的行为,还是一个错误?
3 回答
繁星淼淼
TA贡献1775条经验 获得超11个赞
\n
\n
fflush
printf( "Hello, my pid is %d", getpid() );fflush(stdout);
慕娘9325324
TA贡献1783条经验 获得超4个赞
fork()
fork()
fflush
exec*
fflush
write
_exit
_Exit
exit
- 3 回答
- 0 关注
- 801 浏览
添加回答
举报
0/150
提交
取消