【问题标题】:Daemonizing a child process consequently changes its PID守护子进程因此会更改其 PID
【发布时间】:2015-10-11 13:38:08
【问题描述】:
pid = Process.fork
#sleep 4
Process.daemon nil, true
if pid.nil? then
    job.exec
else
    #Process.detach(pid)
end

Process.fork 返回的pidProcess.daemon(nil, true) 运行后立即更改。有没有办法保存/跟踪随后被守护的分叉子进程的 pid?

我想从父进程中知道子进程的 pid。到目前为止,我能够与 pid 通信的唯一方法是通过IO.pipeProcess.pid 写入 IO#write,然后使用父级的 IO#read 读取它。不太理想

【问题讨论】:

    标签: ruby process multiprocessing fork daemon


    【解决方案1】:

    Process.daemon 是否是自己的分叉,这就是更改 pid 的原因。如果您需要知道守护进程的 pid,为什么不在 if 的分叉部分使用 Process.pid?

    pid = Process.fork
    #sleep 4
    Process.daemon nil, true
    if pid.nil? then
        job.exec
    else
        Process.detach(Process.pid)
    end
    

    【讨论】:

    • 我应该更清楚我想在哪里检索pid。我想知道父进程中的pid。
    【解决方案2】:

    我提出的解决方案涉及使用 Ruby 的 IO 将 pid 从子进程传递给父进程。

    r, w = IO.pipe
    pid = Process.fork
    Process.daemon nil, true
    w.puts Process.pid
    if pid.nil? then
      job.exec
    else
      #Process.detach(pid)
    end
    
    pid = r.gets
    

    另一种解决方案涉及调用具有控制终端的所有进程的process status

    def Process.descendant_processes(base=Process.pid)
    descendants = Hash.new{|ht,k| ht[k]=[k]}
    Hash[*`ps -eo pid,ppid`.scan(/\d+/).map{|x|x.to_i}].each{|pid,ppid|
    descendants[ppid] << descendants[pid]
    }
    descendants[base].flatten - [base]
    end
    

    【讨论】:

      猜你喜欢
      • 2016-05-08
      • 1970-01-01
      • 1970-01-01
      • 2013-06-17
      • 2017-09-09
      • 1970-01-01
      • 2014-10-20
      • 2014-08-30
      • 2014-12-11
      相关资源
      最近更新 更多