I want my program to print something when I terminate it by hitting
control-C. Is this possible? How do you do this in Java?
Thanks!
Rhino - 05 May 2006 04:57 GMT
>I want my program to print something when I terminate it by hitting
> control-C. Is this possible? How do you do this in Java?
You could write a key listener that prints whatever you want whenever CTRL-C
is hit.
See http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html
for an article describing how to write a Key Listener.
--
Rhino
Thomas Schodt - 05 May 2006 05:56 GMT
> I want my program to print something when I terminate it by hitting
> control-C. Is this possible? How do you do this in Java?
<http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#addShutdownHook(j
ava.lang.Thread)>
Not sure if System.out is guaranteed to be available at this point though.
Simon - 05 May 2006 07:23 GMT
> <http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#addShutdownHook(j
ava.lang.Thread)>
>
> Not sure if System.out is guaranteed to be available at this point though.
I'm also not sure about whether or not availability of System.out is guaranteed
in any way, but I'm sure that it worked for me at least once. At least you can
be sure that it does not throw an exception since it is a PrintStream :-)
The docs of addShutdownHook say:
"Uncaught exceptions are handled in shutdown hooks just as in any other thread,
by invoking the uncaughtException method of the thread's ThreadGroup object. The
default implementation of this method prints the exception's stack trace to
System.err and terminates the thread; it does not cause the virtual machine to
exit or halt."
So they also assume that System.err is available.
Cheers,
Simon
Tony Morris - 05 May 2006 05:57 GMT
>I want my program to print something when I terminate it by hitting
> control-C. Is this possible? How do you do this in Java?
>
> Thanks!
You add a "shutdown hook" thread.
See
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runtime.html#addShutdownHook(j
ava.lang.Thread)

Signature
Tony Morris
http://tmorris.net/