Module: Forker
- Defined in:
- lib/forker.rb,
lib/forker/version.rb
Defined Under Namespace
Modules: CLI
Constant Summary collapse
- VERSION =
"1.0.2"
Class Method Summary collapse
Class Method Details
.fork!(opts = {}) ⇒ Object
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'lib/forker.rb', line 57 def self.fork!(opts={}) opts = { :log => "/dev/null", :pid => "/var/run/#{File.basename($0)}.pid" }.merge(opts) $stdout.sync = $stderr.sync = true $stdin.reopen("/dev/null") exit if fork Process.setsid exit if fork Dir.chdir("/") if opts[:chdir] File.umask(0000) if opts[:umask] if File.exist?(opts[:pid]) begin existing_pid = File.read(opts[:pid]).to_i Process.kill(0, existing_pid) # See if proc exists abort "error: existing process #{existing_pid} using this pidfile, exiting" rescue Errno::ESRCH puts "warning: removing stale pidfile with pid #{existing_pid}" end end File.open(opts[:pid], 'w') { |f| f.write($$) } at_exit do ( File.read(opts[:pid]).to_i == $$ and File.unlink(opts[:pid]) ) rescue nil end puts "forked process is #{$$}" puts "output redirected to #{opts[:log]}" $stdout.reopen(opts[:log], 'a') $stderr.reopen(opts[:log], 'a') $stdout.sync = $stderr.sync = true end |
.kill(opts = {}) ⇒ Object
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
# File 'lib/forker.rb', line 96 def self.kill(opts={}) begin pid = File.read(opts[:pid]).to_i sec = 60 # Seconds to wait before force killing Process.kill("TERM", pid) begin SystemTimer.timeout(sec) do loop do puts "waiting #{sec} seconds for #{pid} before sending KILL" Process.kill(0, pid) # See if proc exists sec -= 1 sleep 1 end end rescue Errno::ESRCH puts "killed process #{pid}" rescue Timeout::Error Process.kill("KILL", pid) puts "force killed process #{pid}" end rescue Errno::ENOENT puts "warning: pidfile #{opts[:pid]} does not exist" rescue Errno::ESRCH puts "warning: process #{pid} does not exist" end end |