Skip to content

Instantly share code, notes, and snippets.

@agile
Created April 14, 2009 21:53
Show Gist options
  • Save agile/95452 to your computer and use it in GitHub Desktop.
Save agile/95452 to your computer and use it in GitHub Desktop.
--- /usr/lib/ruby/gems/1.8/gems/analogger-0.5.0/src/swiftcore/Analogger.rb 2009-04-14 16:52:11.000000000 -0500
+++ Analogger.rb 2009-04-14 16:50:16.000000000 -0500
@@ -65,12 +65,63 @@
}
end
- def daemonize
- if (child_pid = fork)
- puts "PID #{child_pid}" unless @config[Cpidfile]
- exit!
- end
- Process.setsid
+ def close_io_handles
+ ObjectSpace.each_object(IO) do |io|
+ unless [STDIN, STDOUT, STDERR].include?(io)
+ begin
+ io.close unless io.closed?
+ rescue Exception
+ end
+ end
+ end
+ end
+
+ def redirect_io
+ begin; STDIN.reopen('/dev/null'); rescue Exception; end
+ begin; STDOUT.reopen('/dev/null'); rescue Exception; end
+ begin; STDERR.reopen(STDOUT); rescue Exception; end
+ STDERR.sync = true
+ end
+
+ def safe_fork
+ begin
+ if pid = fork
+ return pid
+ end
+ rescue Errno::EWOULDBLOCK
+ sleep 5
+ end
+ end
+
+ def daemonize
+ pid = safe_fork and exit!
+ STDOUT.puts "PID #{pid}" unless @config[Cpidfile]
+ if sess_id = Process.setsid
+ #STDERR.puts "setsid #{sess_id}"
+ else
+ STDERR.puts "Could not detach from controlling terminal."
+ end
+ close_io_handles
+ redirect_io
+
+ #if (child_pid = fork)
+ # puts "PID #{child_pid}" unless @config[Cpidfile]
+ # exit!
+ #end
+ #Process.setsid
rescue Exception
puts "Platform (#{RUBY_PLATFORM}) does not appear to support fork/setsid; skipping"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment