1

I'm writing a daemon in Ruby 1.8.7 (i.e., no Process.daemon) using a double-fork + setsid:

exit if fork
Process.setsid
exit if fork

After all of this, I still, for some reason, seem to be able to print out to stdout. From everything I've read, the daemon process should not have a controlling terminal, and writes to stdout should not do anything. However, if I follow up the above with a:

puts "Hello world"

"Hello world" is printed to the screen. Is this expected behavior?

bacchuswng
  • 335
  • 2
  • 9

1 Answers1

0

Yes I believe this is expected. Calling Process.setsid does not close any open file descriptors, you will need to manually reopen them with /dev/null, e.g.:

io = File.open("/dev/null", "w+")

exit if fork
Process.setsid
exit if fork

$stdin.reopen(io)
$stdout.reopen(io)
$stderr.reopen(io)

Or, if you care about the output, you could reopen stdout and stderr with log files.

I would also recommend changing the working directory to / to avoid the daemon running in a non-existent directory:

Dir.chdir("/")
lmars
  • 2,502
  • 1
  • 16
  • 9