Skip to content

Instantly share code, notes, and snippets.

@stevendanna
Last active October 18, 2018 13:48
Show Gist options
  • Save stevendanna/9799477 to your computer and use it in GitHub Desktop.
Save stevendanna/9799477 to your computer and use it in GitHub Desktop.
"Old School" Ruby Daemon Example Code
#!/usr/bin/env ruby
# What does getrlimit tell us?
# What are we doing here and why?
# If we are on linux, is there a better alternative?
(3).upto(Process.getrlimit(Process::RLIMIT_NOFILE)[0]) do |n|
begin
if(fd = File.for_fd(n))
puts "Closing FD #{n}"
fd.close
end
rescue Errno::EBADF, ArgumentError
end
end
# What does the system call fork() do?
# What does fork() return in Ruby or C?
pid1 = Process.fork
if pid1.nil?
puts "[#{Process.pid}] I am the first child."
# What does setsid do here?
# What would happen if we didn't do this?
Process.setsid
pid2 = Process.fork
if pid2.nil?
puts "[#{Process.pid}] I am the second child."
# Where would output go if we didn't do this?
$stdin.reopen("/dev/null")
$stdout.reopen("/dev/null", "a")
$stderr.reopen($stdout)
# What is a umask?
# What is the consequence of doing this?
File.umask 0
# What could happen if we didn't do this?
Dir.chdir "/"
while sleep 5 do
$0 = "my-daemon: still running #{Time.now}"
end
else
exit 0
end
else
exit 0
end
# But wait, there's more!
#
# What didn't we handle that we may have if we were paranoid or a more
# complicated program? Well, why and how would you want to deal with:
#
# - Signal handlers
# - Signal mask
# - Preventing another copy from running if necessary
# - Dropping priviledges
#
# Also if our program was more complicated, we've exited 0 in the top
# level process without knowing if our daemon is completely
# initialized.
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment