Skip to content

Instantly share code, notes, and snippets.

@bemurphy
Forked from djanowski/gist:822356
Created February 11, 2011 16:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bemurphy/822606 to your computer and use it in GitHub Desktop.
Save bemurphy/822606 to your computer and use it in GitHub Desktop.
def daemonize(name = File.basename($0), options = {})
pid_path = options[:pid_path] || File.expand_path("tmp/pids/#{name}.pid")
# If the pid file exists, check that the process is actually still running.
begin
if File.exists?(pid_path) && Process.kill(0, File.read(pid_path).to_i)
$stderr.puts "Already running."
exit 1
end
rescue Errno::ESRCH
File.delete(pid_path)
end
at_exit do
File.delete(pid_path)
logger.error("#{$!.class}: #{$!.message}\n#{$!.backtrace.join("\n")}") if $!
end
Process.daemon(true)
# Open with File::::EXCL, File::CREAT, and perms to avoid race conditions
# (i.e. a malicious symlink in a shared dir)
File.open(pid_path, File::RDWR|File::EXCL|File::CREAT, 0600) { |io| io.write(Process.pid) }
end
@bemurphy
Copy link
Author

not likely it'll race between the lines, but still nice I think.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment