Seph
Seph

Reputation: 1094

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

The pid returned by Process.fork is changed as soon as Process.daemon(nil, true) is run. Is there a way to preserve/track the pid of a forked child process that is subsequently daemonized?

I want to know the pid of the child process from within the parent process. So far the only way I've been able to communicate the pid is through IO.pipe writing the Process.pid to IO#write and then using IO#read from the parent to read it. Less than ideal

Upvotes: 0

Views: 336

Answers (2)

Seph
Seph

Reputation: 1094

The solutions I've come up with involve using Ruby's IO to pass the pid from the child process to the parent.

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

Another solution involves invoking the process status of all processes that have controlling terminals.

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

Upvotes: 0

wired9
wired9

Reputation: 44

Process.daemon does it's own fork, that's why the pid is changed. If you need to know the daemon's pid, why not use Process.pid in the forked part of if?

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

Upvotes: 1

Related Questions