def call_as_daemon(block, logfile_name = nil, app_name = nil)
rd, wr = IO.pipe
if tmppid = safefork
wr.close
pid = rd.read.to_i
rd.close
Process.waitpid(tmppid)
return pid
else
rd.close
unless sess_id = Process.setsid
raise Daemons.RuntimeException.new('cannot detach from controlling terminal')
end
trap 'SIGHUP', 'IGNORE'
exit if pid = safefork
wr.write Process.pid
wr.close
$0 = app_name if app_name
Dir.chdir "/"
File.umask 0000
ObjectSpace.each_object(IO) do |io|
unless [STDIN, STDOUT, STDERR].include?(io)
begin
unless io.closed?
io.close
end
rescue ::Exception
end
end
end
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
block.call
exit
end
end