dfacdfb437b9c5019166da110a146f5dc1f2cbe2
[packages/precise/mcollective.git] / lib / mcollective / unix_daemon.rb
1 module MCollective
2   class UnixDaemon
3     # Daemonize the current process
4     def self.daemonize
5       fork do
6         Process.setsid
7         exit if fork
8         Dir.chdir('/tmp')
9         STDIN.reopen('/dev/null')
10         STDOUT.reopen('/dev/null', 'a')
11         STDERR.reopen('/dev/null', 'a')
12
13         yield
14       end
15     end
16
17     def self.daemonize_runner(pid=nil)
18       raise "The Unix Daemonizer can not be used on the Windows Platform" if Util.windows?
19
20       UnixDaemon.daemonize do
21         if pid
22           begin
23             File.open(pid, 'w') {|f| f.write(Process.pid) }
24           rescue Exception => e
25           end
26         end
27
28         begin
29           runner = Runner.new(nil)
30           runner.run
31         ensure
32           File.unlink(pid) if pid && File.exist?(pid)
33         end
34       end
35     end
36   end
37 end