I want to spawn
a potentially long running process and save its PID so I can kill it later if needed.
The problem is that the PID I get from spawn
is not the same I get from Process.pid
(in the child process). The result of Process.pid
matches what I see running ps
in the command line.
Here is the code for parent and child
parent.rb
puts "Hi parent"
pid = spawn "ruby child.rb 10 &"
puts pid
Process.detach(pid)
sleep 3
puts "Bye parent"
child.rb
puts "Start pid #{Process.pid}"
sleep ARGV.first.to_i
puts "End pid #{Process.pid}"
Output
Hi parent
1886789
Start pid 1886791
Bye parent
End pid 1886791
CodePudding user response:
Looks like the background job operator (&
) is causing the intermediate process 1886789
. When I remove the background job operator, I get the following output:
Hi parent
93185
Start pid 93185
Bye parent
End pid 93185