“file.sync = true”有什么作用?

我查看了文档,但似乎无法找到相关部分。 任何人都可以告诉我以下代码中的sync调用是什么?

 fh = Tempfile.new('tmp') fh.sync = true 

它设置文件的同步模式。

这会影响将来的操作并导致输出在没有块缓冲的情况下写入。

如果f.tty? 是的,也就是说,如果文件连接到类似控制台的设备,则输出不是块缓冲的。 但是当输出到管道或文件时, f.tty? 将为false并且I / O库将切换到块缓冲,即,在缓冲区中累积输出并仅在文件关闭,程序退出或缓冲区填满时写入。 这更快,最终结果是一样的。

设置f.sync = true此开关f.sync = true 。 如果管道的输出连接到实际上是控制台的某些东西或以某种方式交互或者正在主动监视文件的内容,这将非常有用。

基本上,它会立即将缓冲在内存中的所有数据写入磁盘。

Tempfileinheritance自IO。 从IO.sync文档:

  ios.sync -> true or false ------------------------------------------------------------------------------ Returns the current ``sync mode'' of ios. When sync mode is true, all output is immediately flushed to the underlying operating system and is not buffered by Ruby internally. See also IO#fsync. f = File.new("testfile") f.sync #=> false