LoginSignup
11
11

More than 5 years have passed since last update.

Rubyプロセスが今ソースのどの行を実行しているか表示させる(シグナルを利用)

Posted at

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] -------------------

参考
http://varaneckas.com/blog/ruby-tracing-threads-unicorn/

11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11