Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my TERM not being captured

Tags:

linux

unix

ruby

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?

like image 270
Sam Saffron Avatar asked Oct 09 '14 00:10

Sam Saffron


People also ask

What is the meaning of being captured?

to take someone as a prisoner, or to take something into your possession, especially by force: Two of the soldiers were killed and the rest were captured.

What do you call people who are captured?

Definitions of captor. a person who captures and holds people or animals. synonyms: capturer. Antonyms: liberator. someone who releases people from captivity or bondage.

Which word is the opposite of captured '?

Escape means 'to break free' which is the opposite of capture.

Is it capture or captured?

verb (used with object), cap·tured, cap·tur·ing. to take by force or stratagem; take prisoner; seize: The police captured the burglar. to gain control of or exert influence over: an ad that captured our attention; a TV show that captured 30% of the prime-time audience.


1 Answers

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.

like image 140
Sam Saffron Avatar answered Oct 13 '22 01:10

Sam Saffron