Why is my TERM not captured

I have this code example:

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 starts a process that captures TERM, and then sends it TERM.

The problem is that TERM is not fixed here, and the process just ends.

 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 slept after appearing and passed the kill off from another process, the TERM will be 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 

Another shell

 kill -TERM PID 

Output

 GOT TERM 

Moreover, if I then try to kill , the process from the initiating process after it is captured in the TERM handler will no longer kill it.

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

+6
source share
1 answer

Ahh, I get it

TERM is sent to the process too soon before the Ruby interpreter can set the hook. Thus, he completes it.

a sleep 1 to kill -TERM #{pid} sorts the problem.

+11
source

Source: https://habr.com/ru/post/976461/


All Articles