Updated mcollective.init according to OSCI-658
[packages/precise/mcollective.git] / lib / mcollective / unix_daemon.rb
diff --git a/lib/mcollective/unix_daemon.rb b/lib/mcollective/unix_daemon.rb
new file mode 100644 (file)
index 0000000..dfacdfb
--- /dev/null
@@ -0,0 +1,37 @@
+module MCollective
+  class UnixDaemon
+    # Daemonize the current process
+    def self.daemonize
+      fork do
+        Process.setsid
+        exit if fork
+        Dir.chdir('/tmp')
+        STDIN.reopen('/dev/null')
+        STDOUT.reopen('/dev/null', 'a')
+        STDERR.reopen('/dev/null', 'a')
+
+        yield
+      end
+    end
+
+    def self.daemonize_runner(pid=nil)
+      raise "The Unix Daemonizer can not be used on the Windows Platform" if Util.windows?
+
+      UnixDaemon.daemonize do
+        if pid
+          begin
+            File.open(pid, 'w') {|f| f.write(Process.pid) }
+          rescue Exception => e
+          end
+        end
+
+        begin
+          runner = Runner.new(nil)
+          runner.run
+        ensure
+          File.unlink(pid) if pid && File.exist?(pid)
+        end
+      end
+    end
+  end
+end