Rubyスクリプトに予めシグナルハンドラを仕込んでおくことにより、シグナルを送ってその時点で実行していた行(を含むスタックトレース)を表示させる。
スクリプトに仕込むコード
Signal.trap('USR2') do
pid = Process.pid
puts "[#{pid}] Received USR2 at #{Time.now}. Dumping threads:"
Thread.list.each do |t|
trace = t.backtrace.join("\n[#{pid}] ")
puts "[#{pid}] #{trace}"
puts "[#{pid}] ---"
end
puts "[#{pid}] -------------------"
end
サンプルスクリプト
Signal.trap('USR2') do
pid = Process.pid
puts "[#{pid}] Received USR2 at #{Time.now}. Dumping threads:"
Thread.list.each do |t|
trace = t.backtrace.join("\n[#{pid}] ")
puts "[#{pid}] #{trace}"
puts "[#{pid}] ---"
end
puts "[#{pid}] -------------------"
end
puts "pid = #{Process.pid}"
@sum = 0
def add(num)
@sum += num
end
def main
@sum = 0
while true
add(1)
add(2)
add(3)
end
end
main()
実行例
$ kill -USR2 20720
[22108] Received USR2 at 2016-03-23 11:50:10 +0900. Dumping threads:
[22108] hoge.rb:5:in `backtrace'
[22108] hoge.rb:5:in `block (2 levels) in <main>'
[22108] hoge.rb:4:in `each'
[22108] hoge.rb:4:in `block in <main>'
[22108] hoge.rb:17:in `call'
[22108] hoge.rb:17:in `add' ← callの下。ここが実行中だった部分
[22108] hoge.rb:25:in `main'
[22108] hoge.rb:29:in `<main>'
[22108] ---
[22108] -------------------