Module included in classes that can be turned into a daemon. Handle stuff like:
storing the PID in a file
redirecting output to the log file
changing process privileges
killing the process gracefully
Change privileges of the process to the specified user and group.
# File lib/thin/daemonizing.rb, line 66 def change_privilege(user, group=user) log_info "Changing process privilege to #{user}:#{group}" uid, gid = Process.euid, Process.egid target_uid = Etc.getpwnam(user).uid target_gid = Etc.getgrnam(group).gid if uid != target_uid || gid != target_gid # Change PID file ownership File.chown(target_uid, target_gid, @pid_file) if File.exists?(@pid_file) # Change process ownership Process.initgroups(user, target_gid) Process::GID.change_privilege(target_gid) Process::UID.change_privilege(target_uid) end rescue Errno::EPERM => e log_info "Couldn't change user and group to #{user}:#{group}: #{e}" end
Turns the current script into a daemon process that detaches from the console.
# File lib/thin/daemonizing.rb, line 39 def daemonize raise PlatformNotSupported, 'Daemonizing is not supported on Windows' if Thin.win? raise ArgumentError, 'You must specify a pid_file to daemonize' unless @pid_file remove_stale_pid_file pwd = Dir.pwd # Current directory is changed during daemonization, so store it # HACK we need to create the directory before daemonization to prevent a bug under 1.9 # ignoring all signals when the directory is created after daemonization. FileUtils.mkdir_p File.dirname(@pid_file) FileUtils.mkdir_p File.dirname(@log_file) Daemonize.daemonize(File.expand_path(@log_file), name) Dir.chdir(pwd) write_pid_file at_exit do log_info "Exiting!" remove_pid_file end end
Register a proc to be called to restart the server.
# File lib/thin/daemonizing.rb, line 87 def on_restart(&block) @on_restart = block end
# File lib/thin/daemonizing.rb, line 157 def remove_pid_file File.delete(@pid_file) if @pid_file && File.exists?(@pid_file) end
If PID file is stale, remove it.
# File lib/thin/daemonizing.rb, line 168 def remove_stale_pid_file if File.exist?(@pid_file) if pid && Process.running?(pid) raise PidFileExist, "#{@pid_file} already exists, seems like it's already running (process ID: #{pid}). " + "Stop the process or delete #{@pid_file}." else log_info "Deleting stale PID file #{@pid_file}" remove_pid_file end end end
Generated with the Darkfish Rdoc Generator 2.