What does “file.sync = true” do?

前端 未结 3 1022
谎友^
谎友^ 2021-01-17 09:44

I had a look at the docs but I can\'t seem to find the relevant part. Can anyone tell me what the call to sync is for in the following code?

fh          


        
相关标签:
3条回答
  • 2021-01-17 09:56

    It sets the sync mode of the file.

    This affects future operations and causes output to be written without block buffering.

    If f.tty? is true, that is, if the file is connected to a console-like device, then output is not block buffered. But when output goes to a pipe or file, f.tty? will be false and the I/O library will switch to block buffering, that is, accumulating output in a buffer and writing it only if the file is closed, the program exits, or the buffer fills up. This is faster and the end result is the same.

    Setting f.sync = true defeats this switch. This can be useful if the output of the pipe is connected to something that actually is a console or in some way interactive or if the contents of the file are being actively monitored.

    0 讨论(0)
  • 2021-01-17 10:12

    Tempfile inherits from IO. From the IO.sync docs:

      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
    
    0 讨论(0)
  • 2021-01-17 10:15

    Basically, it writes any data buffered in memory out to disk right away.

    0 讨论(0)
提交回复
热议问题