Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Let Java Handle System Interrupts Like Ctrl+C

I have a java program which creates a lock file to ensure that no other executions run at the same time as it. If the program runs it creates the file, and upon exit, either successful or via an exception, the file is removed. But if the user hits Ctrl+C, closes the terminal, or in some other way interrupts execution, the file is not deleted. Is there any way to detect this interrupt command and ensure that the file is deleted in this case as well?

like image 626
dimo414 Avatar asked Aug 04 '09 20:08

dimo414


2 Answers

You might want to look into shutdown hooks.

Also, this is probably a duplicate or near-duplicate of this previous SO question from a day or two ago:

How can I "intercept" Ctrl+C in a CLI application?

like image 150
Amber Avatar answered Sep 20 '22 10:09

Amber


The only good way to deal with this is to timestamp your log file, and update the logfile with a new timestamp every few seconds. File.deleteOnExit will help, but no method is foolproof (what happens when someone just pulls the power cord?).

If you write a timestamp, then you can check for a valid timestamp (recently written) and overwrite the log file if it is too badly out of date. That way a stale lockfile won't get in the way of the user.

like image 42
jsight Avatar answered Sep 18 '22 10:09

jsight