在Ruby中使用双叉创建守护程序 [英] Create a daemon with double-fork in Ruby
问题描述
在Ruby中创建行为良好的Unix或Linux守护程序的正确方法是什么?
井的定义是什么?行为正常的守护程序,以及如何用Ruby编写这样的程序?
What is the definition of a well-behaved daemon anyway, and how would one write such a program in Ruby?
推荐答案
根据Stevens的高级编程UNIX环境》第13章,这是制作行为良好的Unix守护程序的过程:
According to Stevens's Advanced Programming in the UNIX Environment chapter 13, this is the procedure to make a well-behaved Unix daemon:
- Fork并有一个父级出口。这使Shell或引导脚本认为命令已完成。此外,保证子进程不会成为进程组负责人(下一个setsid的先决条件)
- 调用
setsid
创建一个新会议。这会做三件事:
- Fork and have the parent exit. This makes the shell or boot script think the command is done. Also, the child process is guaranteed not to be a process group leader (a prerequisite for setsid next)
- Call
setsid
to create a new session. This does three things:
- 该流程成为新会话的会话负责人
- 该流程成为流程组新流程组的负责人
- 该流程没有控制终端
/
避免干扰安装和卸载 stdout
, stderr
和 stdin
。
/
to avoid interfering with mounting and unmountingstdout
, stderr
, and stdin
.如今,有一个文件可以跟踪Linux大量使用的PID分发启动脚本。请确保写出孙子的PID,即第二个fork的返回值(步骤3)或步骤3之后的 getpid()
值。
Nowadays there is a file to track the PID which is used heavily by Linux distribution boot scripts. Be sure to write out the PID of the grandchild, either the return value of the second fork (step 3) or the value of getpid()
after step 3.
这里是一个Ruby实现,主要是从书中翻译过来的,但是带有双叉并写出了守护进程PID。
Here is a Ruby implementation, mostly translated from the book, but with the double-fork and writing out the daemon PID.
# Example double-forking Unix daemon initializer.
raise 'Must run as root' if Process.euid != 0
raise 'First fork failed' if (pid = fork) == -1
exit unless pid.nil?
Process.setsid
raise 'Second fork failed' if (pid = fork) == -1
exit unless pid.nil?
puts "Daemon pid: #{Process.pid}" # Or save it somewhere, etc.
Dir.chdir '/'
File.umask 0000
STDIN.reopen '/dev/null'
STDOUT.reopen '/dev/null', 'a'
STDERR.reopen STDOUT
这篇关于在Ruby中使用双叉创建守护程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!