守护子进程因此改变其PID

时间:2015-07-21 21:51:44

标签: ruby process multiprocessing fork daemon

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

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我提出的解决方案涉及使用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