简体   繁体   中英

How to trap signal in Ruby process

I want to trap a signal sent to a Ruby process.

The process is the following file, called wait.rb:

sleep 60

Signal.trap(15) {
  puts "caught signal 15!"
}

I run wait.rb, and in another bash shell find the PID of wait.rb and execute:

kill -15 pid

I expected that "caught signal 15!" would be printed in the first shell where I executed wait.rb, but it is not. Instead, I get this output:

Terminated: 15

Why is the puts statement in the Signal.trap block not executed?

You need to sleep after you run your code to trap the signal. It will still be sleeping when you send the signal, and the code to trap it has not yet run.

This code will trap your signal:

Signal.trap(15) {
  puts "caught signal 15!"
}

sleep 60

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