Search code examples
terminalconsolehaxegetchar

haxe cpp - How to catch Ctrl+C key press in terminal application?


I've made terminal application that gets keyboard input by Sys.getChar(). While collecting chars of command I can catch any system key codes like Ctrl+C and process them. But when I run massive calculations after entering command, any Ctrl+C key press aborts application immediately.

I'd like to catch Ctrl+C not only in terminal input mode but while inner functions are running for valid interrupt processing. Method Sys.getChar() can't do that because it's blocking. Is there any methods to catch global application abort event or seamlessly read keyboard buffer without blocking runtime process?


Solution

  • Haxe doesn't provide this functionality in the std lib. However, you may use raw cpp code to do this

    Test.hx:

    @:headerCode("#include <csignal>")
    @:cppFileCode("
    void _handler(int sig) {
        Test_obj::handler(sig);
    }
    ")
    class Test {
        static var sig:Int = -1;
        static function handler(_sig:Int):Void {
            sig = _sig;
        }
        static function main():Void {
            untyped __cpp__("signal(SIGINT, &_handler);");
            while (true) {
                Sys.sleep(0.1); //reduce cpu usage
                switch (sig) {
                    case -1:
                        //there is no signal received yet
                    case 2:
                        trace("ctrl-c is pressed.");
                        Sys.exit(0);
                    default:
                        trace('Got signal: $sig');
                }
            }
        }
    }
    

    Note that I've only tested it on Mac.

    The usage of @: matadata can be found at http://haxe.org/manual/cr-metadata.html