How is CTRL+C handled in jline2

I had a hard time trying to understand how is CTRL+C handled in jline2. I found in consoleReader.readline an exception will be thrown if handleUserInterrupt is set to true. But I wonder before this exception is thrown, how is CTRL+C is trapped and interpreted (instead of exiting the program)?

Answer

UserInterruptException will be thrown only from one of the ConsoleReader.readLine methods and only when the user press CTRL+C and handleUserInterrupt is set to true (by calling consoleReader.setHandleUserInterrupt(true)).

On UNIX Platforms

Only if the terminal of the ConsoleReader is an instance of UnixTerminal (the default terminal for UNIX platforms), it’s disableInterruptCharacter method is called when readLine is called. This method disables the default behavior of CTRL+C (usually causes the JVM to exit) by executing proper command to the system (by using stty). Before the readLine method returns, it calls the enableInterruptCharacter method of the terminal, which enables the default behavior of CTRL+C.

This means that the default behavior of CTRL+C is disabled only when the readLine method is executing.

Leave a Reply

Your email address will not be published. Required fields are marked *