守护一个子进程因此改变了它的 PID

Daemonizing a child process consequently changes its PID

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

一旦 Process.daemon(nil, true) 为 运行,Process.fork 返回的 pid 就会更改。有没有办法 preserve/track 随后被守护进程的分叉子进程的 pid?

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

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

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