简体   繁体   中英

Why is my TERM not being captured

I have this sample code:

pid = Process.spawn("exec ruby -e \"trap('TERM'){ puts 'GOT TERM'; sleep 100; }; sleep 100\"")
Thread.new do
  Process.wait(pid)
end

p `ps aux | grep #{pid} | grep -v grep`

`kill -TERM #{pid}`
sleep 1

p `ps aux | grep #{pid} | grep -v grep`

It spawns a process that captures TERM and then sends a TERM to it.

Trouble is, TERM is not being captured here and process simply terminates.

ruby test.rb
"sam       8828  0.0  0.0  30576  5052 pts/9    Rl+  11:48   0:00 ruby -e trap('TERM'){ puts 'GOT TERM'; sleep 100; }; sleep 100\n"
""

However ... If I just sleep after the spawn and issue the kill from a different process the TERM is captured as expected.

pid = Process.spawn("exec ruby -e \"trap('TERM'){ puts 'GOT TERM'; sleep 100; }; sleep 100\"")
Thread.new do
  Process.wait(pid)
end
puts pid
sleep 100

Other shell

kill -TERM PID

Output

GOT TERM

Further more, if I try to then kill the process from the originating process after its trapped in the handler TERM will no longer kill it.

What is going on here, why is TERM not being delivered correctly to my child process from the parent?

Ahh, I get it,

TERM is being sent to the process too early, before the Ruby interpreter was able to establish the hook. So it terminates it.

a sleep 1 before kill -TERM #{pid} sorts the issue out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM