I’m using Ruby 1.9.2-p180 on Ubuntu 12.04. I don’t understand why the following code doesn’t work. The expected behaviour is that I should see the text: “TRAPPED” on my screen when I run the code, and the program should terminate. But the ruby program doesn’t terminate when I run it and nothing is printed on the screen. What am I missing?
pid = fork do
exec "trap 'echo TRAPPED' TERM; while :; do :; done"
end
Process.kill("TERM", pid)
Process.wait(pid)
The reason why it did not work as expected was that the kill was delivered before the exec commenced. Introducing a little sleep before delivering the kill ensures that the program will behave as expected.