lib/daemons/daemonize.rb in daemons-0.2.1 vs lib/daemons/daemonize.rb in daemons-0.3.0

- old
+ new

@@ -111,11 +111,11 @@ end module_function :safefork # This method causes the current running process to become a daemon - def daemonize(oldmode=0) + def daemonize(logfile_name = nil, oldmode=0) srand # Split rand streams between spawning and daemonized process safefork and exit # Fork and exit from the parent # Detach from the controlling terminal unless sess_id = Process.setsid @@ -132,18 +132,37 @@ File.umask 0000 # Insure sensible umask # Make sure all file descriptors are closed ObjectSpace.each_object(IO) do |io| unless [STDIN, STDOUT, STDERR].include?(io) - unless io.closed? - io.close rescue nil + begin + unless io.closed? + io.close + end + rescue ::Exception end end end - STDIN.reopen "/dev/null" # Free file descriptors and - STDOUT.reopen "/dev/null", "a" # point them somewhere sensible - STDERR.reopen STDOUT # STDOUT/STDERR should go to a logfile + # Free file descriptors and + # point them somewhere sensible + # STDOUT/STDERR should go to a logfile + + STDIN.reopen "/dev/null" rescue nil + + if logfile_name + begin + STDOUT.reopen logfile_name, "a" + rescue ::Exception + STDOUT.reopen "/dev/null" rescue nil + end + else + STDOUT.reopen "/dev/null" rescue nil + end + + STDERR.reopen STDOUT rescue nil + + return oldmode ? sess_id : 0 # Return value is mostly irrelevant end module_function :daemonize end