Created
June 26, 2013 12:33
-
-
Save maxencehenneron/5867043 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'daemons' | |
# This file will contain all System calls by the program. | |
# (ie : Launching a programm, monitoring it) | |
# Returns the pid of the child that executes the cmd | |
module Monitor | |
module System | |
extend self | |
def daemonize(cmd, options = {}) | |
rd, wr = IO.pipe | |
#the fork call returns twice, once in the parent, returning the process ID of the child, and once in the child, returning nil. The child process can exit using Kernel.exit | |
if child = Daemonize.safefork | |
#We are in the parent, Process.detach register disinterest in their status; otherwise, the operating system may accumulate zombie processes. | |
::Process.detach(child) | |
wr.close | |
daemon_id = rd.read.to_i | |
rd.close | |
return daemon_id if daemon_id > 0 | |
else | |
# child | |
rd.close | |
set_user(options[:utilisateur]) if !options[:utilisateur].nil? | |
to_daemonize = lambda do | |
Dir.chdir(ENV['PWD'] = options[:working_dir].to_s) if options[:working_dir] | |
::Kernel.exec(*Shellwords.shellwords(cmd)) | |
exit | |
end | |
daemon_id = Daemonize.call_as_daemon(to_daemonize, nil, cmd) | |
File.open(options[:pid_file], 'w') {|f| f.write(daemon_id)} | |
wr.write daemon_id | |
wr.close | |
exit | |
end | |
#Launch the program as a specific User. | |
def set_user(uid) | |
if ::Process::Sys.geteuid == 0 | |
uid_num = Etc.getpwnam(uid).uid if uid | |
::Process::Sys.setuid(uid_num) if uid | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment