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 processs privileges
killing the process gracefully
Change privileges of the process to the specified user and group.
# File lib/thin/daemonizing.rb, line 65
65: def change_privilege(user, group=user)
66: log ">> Changing process privilege to #{user}:#{group}"
67:
68: uid, gid = Process.euid, Process.egid
69: target_uid = Etc.getpwnam(user).uid
70: target_gid = Etc.getgrnam(group).gid
71:
72: if uid != target_uid || gid != target_gid
73: # Change process ownership
74: Process.initgroups(user, target_gid)
75: Process::GID.change_privilege(target_gid)
76: Process::UID.change_privilege(target_uid)
77: end
78: rescue Errno::EPERM => e
79: log "Couldn't change user and group to #{user}:#{group}: #{e}"
80: end
Turns the current script into a daemon process that detaches from the console.
# File lib/thin/daemonizing.rb, line 38
38: def daemonize
39: raise PlatformNotSupported, 'Daemonizing is not supported on Windows' if Thin.win?
40: raise ArgumentError, 'You must specify a pid_file to daemonize' unless @pid_file
41:
42: remove_stale_pid_file
43:
44: pwd = Dir.pwd # Current directory is changed during daemonization, so store it
45:
46: # HACK we need to create the directory before daemonization to prevent a bug under 1.9
47: # ignoring all signals when the directory is created after daemonization.
48: FileUtils.mkdir_p File.dirname(@pid_file)
49: FileUtils.mkdir_p File.dirname(@log_file)
50:
51: Daemonize.daemonize(File.expand_path(@log_file), name)
52:
53: Dir.chdir(pwd)
54:
55: write_pid_file
56:
57: at_exit do
58: log ">> Exiting!"
59: remove_pid_file
60: end
61: end
Register a proc to be called to restart the server.
# File lib/thin/daemonizing.rb, line 83
83: def on_restart(&block)
84: @on_restart = block
85: end
# File lib/thin/daemonizing.rb, line 157
157: def remove_pid_file
158: File.delete(@pid_file) if @pid_file && File.exists?(@pid_file)
159: end
If PID file is stale, remove it.
# File lib/thin/daemonizing.rb, line 168
168: def remove_stale_pid_file
169: if File.exist?(@pid_file)
170: if pid && Process.running?(pid)
171: raise PidFileExist, "#{@pid_file} already exists, seems like it's already running (process ID: #{pid}). " +
172: "Stop the process or delete #{@pid_file}."
173: else
174: log ">> Deleting stale PID file #{@pid_file}"
175: remove_pid_file
176: end
177: end
178: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.