Created
March 24, 2011 12:09
-
-
Save Paxa/884948 to your computer and use it in GitHub Desktop.
This file contains 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
module Minion | |
module Daemon | |
extend self | |
attr_accessor :pid, :log | |
def fork_or_skip | |
arg = ARGV.join(" ")[/\-d\s\d+/] || ARGV.join(" ")[/\-d/] | |
return unless arg | |
workers = (arg[/\d+/] || 1).to_i | |
ensure_dirs | |
workers.times do |process_num| | |
if child_pid = fork() # parent process | |
p [process_num, workers] | |
next if process_num < workers - 1 | |
exit if process_num == workers - 1 | |
end | |
puts "started #{process_num} #{Process.pid()}" | |
Process.setsid() | |
try_kill_previous(process_num) unless pid | |
write_pid(process_num) unless pid | |
write_logs(process_num) | |
end | |
end | |
def pid_folder | |
File.basedir(pid) | |
end | |
def log_folder | |
File.basedir(log) | |
end | |
def ensure_dirs | |
`mkdir -p #{pid_folder}` if pid | |
`mkdir -p #{log_folder}` if log | |
end | |
def file_for(method, number) | |
send(method) + ".#{number}" | |
end | |
def write_pid(number) | |
return | |
File.open(file_for(:pid, number), 'w') {|file| file.write(Process.pid())} | |
end | |
def write_logs(number) | |
#$stdin.close() | |
if log | |
$stdout.reopen(file_for(:pid, number) + '.log', "w") | |
$stderr.reopen(file_for(:pid, number) + '.err', "w") | |
else | |
#$stdout.reopen('/dev/null', "w") | |
#$stderr.reopen('/dev/null', "w") | |
end | |
end | |
def try_kill_previous(number) | |
return unless pid | |
pidfile = file_for(:pid, number) | |
if File.exist?(pidfile) | |
pid_to_kill = File.open(pidfile) {|f| f.read } | |
Process.kill("HUP", pid_to_kill) | |
Process.wait | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment