Posted By

nialace on 11/21/10


Tagged


Versions (?)

hooked ctrl-c


 / Published in: Java
 

to shutdown a program with ctrl-c

  1. public class MonExample {
  2.  
  3. protected boolean isRunning = false;
  4.  
  5. [...]
  6.  
  7. protected void init() throws Exception {
  8. // Setup a hook to clean the resources when the CTRL-C key is stroken
  9.  
  10. Runtime.getRuntime().addShutdownHook(new ResourcesCleaner(this));
  11. initOtherClasses();
  12. isRunning = true;
  13. }
  14.  
  15. [...]
  16.  
  17. public void shutdown() throws Exception {
  18. shutdownOtherClasses();
  19.  
  20. isRunning = false;
  21. }
  22.  
  23. [...]
  24.  
  25. protected class ResourcesCleaner extends Thread {
  26.  
  27. // This class is an helper class to manage the CTRL-C stop of the
  28. // application
  29.  
  30. protected MonExample monExample = null;
  31.  
  32. public ResourcesCleanerMonExample monExample {
  33. monExample = monExample
  34. }
  35.  
  36. public void run() {
  37. try {
  38.  
  39. if(isRunning)
  40. monExample.shutdown();
  41. } catch (Exception e) {
  42. STLogger.error("MonExample", "Error while shutting down MonExample", e);
  43.  
  44. }
  45. }
  46. }
  47. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: nialace on November 21, 2010

to shutdown a program with ctrl-c

You need to login to post a comment.