Search code examples
rubyio-redirectiondev-null

What's the significance of specifying a file mode when reopening STDOUT to /dev/null?


I'm reading an example ruby script that creates a daemon by forking, creating a new session, forking again, then redirecting stdin, stdout, stderr to /dev/null

Here's a snippet of the redirection:

STDIN.reopen '/dev/null'
STDOUT.reopen '/dev/null', 'a'
STDERR.reopen '/dev/null', 'a'

What's the significance of specifying the file mode ('a') in this case? Would the behavior be any different, for example, with

STDOUT.reopen '/dev/null', 'w'

or even

STDOUT.reopen '/dev/null'

?


Solution

  • There's no particular significance, but it's semantically helpful to a reader who would expect that STDOUT is append or write, but not read. It's also defensive against the default (typically read) changing in the future, unlikely as that may be. In fact Ruby has protections against changing the mode of STDIN or STDOUT.

    STDOUT.reopen '/dev/null', 'r'
    
    test.rb:1:in `reopen': <STDOUT> can't change access mode from "w" to "r" (ArgumentError)
    from test.rb:1:in `<main>'
    

    This does work on other IOs though, and it's always nice to be explicit.

    f = File.open('file.out', 'w')
    f.puts 'Hi'
    f.close
    
    f.reopen('file.out', 'r')
    puts f.read
    
    $ ruby test.rb
    Hi