2010-09-10 132 views

回答

17

使用Daemonize.rb

require 'daemons' 
Daemons.daemonize 

很簡單的例子:http://github.com/utkarsh2012/backitup/blob/master/backitup.rb

如何安裝守護寶石:

gem install daemons 
+0

這可能是一個愚蠢的問題,但daemonize.rb文件在哪裏?它是一顆寶石,在網上我能找到它的地方,它是標準庫,還是什麼? – agentbanks217 2010-09-10 23:05:24

+0

這是一顆寶石。你只需安裝並開始使用它。 – zengr 2010-09-10 23:13:08

+0

好的非常感謝。 – agentbanks217 2010-09-10 23:51:07

3

這是一個module來守護您的代碼。這是一個包含現有腳本的offshoot

本質上,它歸結爲這個(特拉維斯威頓的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 
+0

馬克,而這是正確的代碼更多的香草Unix系統,它會或多或少的在Mac OS X上工作,這實際上不是正確的配方......我沒有一個可以方便地用launchd註冊ruby腳本的罐裝食譜,但那就是OP可能應該在尋找。 :-) – 2010-09-10 21:52:43

+0

@凱林,優點。我應該更仔細地閱讀這個問題。不幸的是,我並不是沒有任何關於沒有Mac ... – Mark 2010-09-10 21:57:21

+0

偉大的解釋。 – zee 2016-10-06 01:29:10

27

的Ruby 1.9.x的已執行以下操作:

Process.daemon 

把它放在你的代碼中,就是這樣。

來自「Daemon Processes in Ruby」。

+1

它不適用於Windows。 – Olathe 2013-02-12 17:50:33

3

需要看到後臺程序導軌寶石爲Rails 3(基於rails_generator):

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

可以生成守護存根這樣的:

rails generate daemon <name> 

特點:

  • individual con每個守護特倫腳本
  • 耙:每守護守護命令
  • Capistrano的友好
  • 應用範圍的控制腳本
  • 監測API
  • 可能多個後臺程序設置