Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | CLI | Play Well with Others | Trapping Signals Sent from Other Apps

概要

書籍 Build Awesome Command-Line Applications in Ruby2

Play Well with Others

詳細

長い処理を行うアプリケーションを作った場合などに、途中で処理を中止することがあります。
そのような際に行う処理を記述しておき、中途半端な処理にならないようにする必要があります。

サンプルコード

Signal.trap("SIGINT") do
  puts "interrupted"
  exit false
end
sleep 5

puts "not interrupted"

出力

# 終了まで待たずにCtrl+Cを押した場合
$ ruby 1.rb 
^Cinterrupted

# 終了まで待った場合
$ ruby 1.rb 
not interrupted