How to capture Ctrl-c in Java(console or event) - cross platform

T

Terry Xie

Please give some hints on how to capture ctrl-c so that

resources/files can be released/closed.

Thank you,
Terry
 
T

Tony Morris

@see java.lang.Runtime#addShutdownHook(java.lang.Thread)

--
Tony Morris
(BInfTech, Cert 3 I.T., SCJP[1.4], SCJD)
Software Engineer
IBM Australia - Tivoli Security Software
(2003 VTR1000F)
 
I

Igor N. Kolomiyets

Terry Xie said:
Please give some hints on how to capture ctrl-c so that

resources/files can be released/closed.

Thank you,
Terry

First create a class something like:

class CMailQueueShutdown extends Thread
{
private Timer m_oTimer;
public CMailQueueShutdown(Timer p_oTimer)
{
super();
m_oTimer = p_oTimer;
}

public void run()
{
CDataSource.log("*********************Stopping
session.***********************");
System.out.println("Closing down.");
m_oTimer.cancel();
}
}

and then somewhere in your main method add the following:

final Timer queueRunner = new Timer();
Runtime.getRuntime().addShutdownHook(new CMailQueueShutdown(queueRunner));

It works allright with JDK later then 1.3

Best regards,
Igor.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top