C-fork和printf行为 [英] C - fork and printf behavior

查看:111
本文介绍了C-fork和printf行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

结合使用printf测试fork函数,我发现了一些奇怪的行为

Testing the fork function in combination with printf i found some strange behavior

例如,代码:

int main(){
     if(fork()==0){
          printf("TestString");
     }
}

一会儿什么也不打印

int main(){
  if(fork()==0) {
     printf("TestString\n");
  }
}

正确打印出TestString.为什么打印新行会改变行为?我怀疑它可能对fflush()起作用,但是我不确定.我可以得到解释和链接,或者可以在其中阅读的链接吗?谢谢您的提前答复.

prints out TestString correctly. Why does printing a new line change the behavior? I suspect it might do something with fflush(), but i am not sure. Could i get and explanation or a link where i can read up on it? Thank you for the answer in advance.

我正在寻找的解释是实际上是什么刷新以及为什么\ n与刷新相同.

EDITED: The explanation i am looking for is what is actually flushing and why is \n same as flushing.

推荐答案

在Linux(至少)上,stdout行缓冲.这意味着您写入的所有内容都不会真正出现在屏幕上,直到遇到'\n'为止.如果您不喜欢这种行为,则可以使用setbuf()更改缓冲策略,但是您必须在程序启动后立即执行(实际上,在对流进行任何写入之前),或者在任何时候调用fflush()如您所说,您想刷新缓冲区内容.

On Linux (at least), stdout is line buffered. This means that anything you write to it will not actually appear on the screen until a '\n' is encountered. If you don't like this behaviour you can change the buffering policy with setbuf(), but you will have to do it as soon as your program starts (well, actually before any writes to the stream), or call fflush() whenever you want to flush the buffer contents, as you said.

请记住,当程序结束并且其打开的流自动关闭时,无论如何缓冲区也会被刷新.

Remember that buffers are also flushed anyway when a program ends and its opened streams are automatically closed.

这篇关于C-fork和printf行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆