JavaでC-cした時の処理
シャットダウン時に走るスレッドを用意してRuntimeに渡す.
参考:日記(仮) >> Javaプログラム終了時に確実に終了処理をする
ミニマルなコードはこんな感じか
public class ShutdownHookSample { public static void main(String[] args) { // Set thread to be run when Runtime is shut down. Runtime.getRuntime().addShutdownHook( new Thread(){ @Override public void run(){ System.out.println("\nBye."); } }); System.out.println("Started. (C-c to shut me down.)"); while(true); // Control will never reach here. } }
実行結果例
Started. (C-c to shut me down.) ^C Bye.