如何解决c中多进程输出有什么问题?
我有以下代码:
int main()
{
for (int i = 0; i < 3; i++) {
int t = fork();
if (t == 0) {
printf("child %d id: %ld from pid: %ld\n",i,(long)getpid(),(long)getppid());
exit(0);
}
else if (t > 0) {
wait(NULL);
printf("father %d id: %ld from pid: %ld\n",(long)getppid());
}
}
return(0);
}
当我运行时,输出是:
当我在 t>0 时删除 printf 中的 "\n" 时,输出为:
第二个输出如何打印比第一个多?请!!
解决方法
您需要记住,printf
不一定会导致写入任何数据。相反,printf
只是将数据写入根据需要刷新的内部缓冲区。
让我们稍微简化一下代码并展开循环来检查发生了什么
int
main(void)
{
int t,i = 0;
t = fork();
if( t == 0 ) {
printf("child %d id: %ld from pid: %ld\n",i,(long)getpid(),(long)getppid());
exit(0);
} else if( t > 0 ) {
wait(NULL);
printf("parent %d id: %ld from pid: %ld",(long)getppid());
}
/* The output buffer now contains "parent N id ..."
but the parent has not yet written any data. */
i += 1;
t = fork();
if( t == 0 ) {
/* Here,the output buffer still contains "parent N id ..." */
printf("child %d id: %ld from pid: %ld\n",(long)getppid());
/* The newline above causes the buffer to be flushed,so now this child writes "parent N id ...child M id: ..." */
exit(0);
...
如果您在父级的 printf 中包含 \n
,这会导致(在某些情况下)输出缓冲区被刷新,以便在您调用 fork
时它是空的,并且子级不会写入附加数据。请注意,如果您将输出重定向到文件,您可能会得到不同的行为,因为在这种情况下 \n
可能不会导致刷新。如果要确保在任何给定点刷新缓冲区,请调用 fflush
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。