进程妖魔化后重新打开文件

时间:2018-12-06 22:21:46

标签: ruby sidekiq

我在Sidekiq中发现了与进程妖魔化有关的下一段代码:

  files_to_reopen = []
  ObjectSpace.each_object(File) do |file|
    files_to_reopen << file unless file.closed?
  end

  ::Process.daemon(true, true)

  files_to_reopen.each do |file|
    begin
      file.reopen file.path, "a+"
      file.sync = true
    rescue ::Exception
    end
  end

  [$stdout, $stderr].each do |io|
    File.open(options[:logfile], 'ab') do |f|
      io.reopen(f)
    end
    io.sync = true
  end
  $stdin.reopen('/dev/null')

https://github.com/mperham/sidekiq/blob/master/lib/sidekiq/cli.rb#L191-L212

我不明白为什么我们必须重开文件才能继承双叉文件描述符?这样做是否存在某些特定情况?"Advanced Programming in the UNIX Environment"书的“守护进程”一章的作者,仅说有关关闭不需要的文件描述符:

  
      
  1. 不需要的文件描述符应关闭。这样可以防止守护程序打开可能已从其父级继承的任何描述符(可能是shell或其他进程)。我们可以使用open_max函数(图2.17)或getrlimit函数(第7.11节)来确定最高的描述符,并关闭所有描述符直至该值。
  2.   

1 个答案:

答案 0 :(得分:1)

我相信大部分代码都是受独角兽启发的。 Unicorn的作者Eric Wong是Ruby世界中的Linux先生,通常知道正确完成守护程序的所有技巧。

当然,从广义上讲,不要守护。您应该使用适当的流程主管来启动Sidekiq:systemd,upstart,runit,领班等。

相关问题