Home > Java > javaTutorial > How to Gracefully Intercept Ctrl C in a Java Command Line Application?

How to Gracefully Intercept Ctrl C in a Java Command Line Application?

Patricia Arquette
Release: 2024-10-29 17:14:02
Original
537 people have browsed it

How to Gracefully Intercept Ctrl C in a Java Command Line Application?

Intercepting Ctrl C in a Command Line Application

Intercepting Ctrl C in a CLI Java application allows a different action to be executed instead of the default behavior of terminating the process. Here's a solution to achieve this using platform-specific methods:

Java

Java provides the Runtime.addShutdownHook() method that creates an exit handler thread which runs code when the JVM is shutting down. However, this will only intercept Ctrl C as an intermediate step before the JVM completely closes.

Signal Handling

For cross-platform signal handling, you can use SignalHandler from the sun.misc package. This approach allows intercepting the SIGINT signal caused by Ctrl C on Unix-like systems (including Linux and Solaris).

Example

<code class="java">import sun.misc.Signal;

public class CtrlCInterceptor {

    public static void main(String[] args) {
        Signal.handle(new Signal("INT"), signal -> {
            // Handle Ctrl+C gracefully
            System.out.println("Ctrl+C pressed. Performing cleanup actions...");
        });
    }
}</code>
Copy after login

This code registers a handler for the "INT" signal (Ctrl C) and prints a message when it's received. You can perform any necessary cleanup actions within the handler block.

The above is the detailed content of How to Gracefully Intercept Ctrl C in a Java Command Line Application?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template