2015-07-21 52 views
0
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?Daemonizing子進程因此改變其PID

我想知道從父進程內的子進程的PID。到目前爲止,我只能通過IO.pipeProcess.pid寫入IO#寫入,然後使用從父節點讀取的IO#讀取它。不理想

回答

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 
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 
+0

我應該更清楚我要檢索'pid'的位置。我想知道父進程中的pid。 – Seph