【问题标题】:haxe cpp - How to catch Ctrl+C key press in terminal application?haxe cpp - 如何在终端应用程序中捕获 Ctrl+C 按键?
【发布时间】:2014-02-02 09:41:33
【问题描述】:

我已经制作了通过 Sys.getChar() 获取键盘输入的终端应用程序。在收集命令字​​符时,我可以捕获任何系统键代码,如 Ctrl+C 并处理它们。但是当我在输入命令后运行大量计算时,任何 Ctrl+C 键都会立即中止应用程序。

我想捕捉 Ctrl+C 不仅在终端输入模式下,而且在内部函数正在运行以进行有效的中断处理时。方法 Sys.getChar() 不能这样做,因为它是阻塞的。有什么方法可以在不阻塞运行时进程的情况下捕获全局应用程序中止事件或无缝读取键盘缓冲区?

【问题讨论】:

    标签: terminal console haxe getchar


    【解决方案1】:

    Haxe 在标准库中不提供此功能。但是,您可以使用原始 cpp 代码来执行此操作

    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');
                }
            }
        }
    }
    

    请注意,我只在 Mac 上测试过。

    @:matadata的用法可以在http://haxe.org/manual/cr-metadata.html找到

    【讨论】:

      猜你喜欢
      • 2011-01-15
      • 1970-01-01
      • 2010-11-20
      • 1970-01-01
      • 2010-09-15
      • 1970-01-01
      • 2013-12-01
      • 2012-03-17
      • 1970-01-01
      相关资源
      最近更新 更多