使Ruby程序成为一个守护进程?

我想写一个Ruby程序,它总是在我的Mac上运行在后台(一个守护进程)。

有人能指出我如何做到这一点的正确方向?

使用Daemonize.rb

require 'daemons' Daemons.daemonize 

非常简单的样本: http : //github.com/utkarsh2012/backitup/blob/master/backitup.rb

如何安装守护进程gem:

 gem install daemons 

Ruby 1.9.x现在有以​​下内容:

 Process.daemon 

把它放在你的代码中,就是这样。

摘自“ Ruby中的守护进程 ”。

啊,谷歌救援! 查看

http://fitzgeraldsteele.wordpress.com/2009/05/04/launchd-example-start-web-server-at-boot-time/

其中一个有用的博主提供了编写一个launchd plist来启动一个ruby Web应用服务器的例子。

这是一个守护代码的模块 。 这是包装现有脚本的分支 。

从本质上讲,它归结为此(来自Travis Whitton的Daemonize.rb,上面的第一个链接,修改了我之前写的一些程序):

 private # This method causes the current running process to become a daemon # If closefd is true, all existing file descriptors are closed def daemonize(pathStdErr, oldmode=0, closefd=false) srand # Split rand streams between spawning and daemonized process safefork and exit# Fork and exit from the parent # Detach from the controlling terminal unless sess_id = Process.setsid raise 'Cannot detach from controlled terminal' end # Prevent the possibility of acquiring a controlling terminal if oldmode.zero? trap 'SIGHUP', 'IGNORE' exit if pid = safefork end Dir.chdir "/" # Release old working directory File.umask 0000 # Insure sensible umask if closefd # Make sure all file descriptors are closed ObjectSpace.each_object(IO) do |io| unless [STDIN, STDOUT, STDERR].include?(io) io.close rescue nil end end end STDIN.reopen "/dev/null" # Free file descriptors and STDOUT.reopen "/dev/null" # point them somewhere sensible STDERR.reopen pathStdErr, "w" # STDOUT/STDERR should go to a logfile return oldmode ? sess_id : 0 # Return value is mostly irrelevant end # Try to fork if at all possible retrying every 5 sec if the # maximum process limit for the system has been reached def safefork tryagain = true while tryagain tryagain = false begin if pid = fork return pid end rescue Errno::EWOULDBLOCK sleep 5 tryagain = true end end end 

需要查看Rails 3的daemons-rails gem(基于rails_generator):

https://github.com/mirasrael/daemons-rails

可以像这样生成守护进程存根:

 rails generate daemon  

特征:

  • 每个守护进程的单独控制脚本
  • rake:每个守护进程的守护进程命令
  • 卡皮斯特拉诺友好
  • 应用程序范围的控制脚本
  • 监控API
  • 可能的多个守护进程集