7

怎么可能Ctrl+C在当前进程的 Dart 程序中捕获

与 Node 类似的东西:

process.on('SIGINT', function() {
    // do stuff
});
4

2 回答 2

7

我在 Unified Diff 找到了以下测试代码:tests/standalone/io/signals_test_script.dart

import "dart:io";

void main(args) {
  int usr1Count = int.parse(args[0]);
  int usr2Count = int.parse(args[1]);
  var sub1;
  var sub2;
  void check() {
    if (usr1Count < 0 || usr2Count < 0) exit(1);
    if (usr1Count == 0 && usr2Count == 0) {
      sub1.cancel();
      sub2.cancel();
    }
    print("ready");
  }
  sub1 = ProcessSignal.SIGUSR1.watch().listen((signal) {
    if (signal != ProcessSignal.SIGUSR1) exit(1);
    usr1Count--;
    check();
  });
  sub2 = ProcessSignal.SIGUSR2.watch().listen((signal) {
    if (signal != ProcessSignal.SIGUSR2) exit(1);
    usr2Count--;
    check();
  });
  check();
}
于 2013-12-19T18:34:48.127 回答
5

看起来旧答案中使用的SIGUSR1and字段现在已弃用。我得到了使用该字段的以下示例:SIGUSR2sigint

import "dart:io";

void main() {
  var n = 0;
  ProcessSignal.sigint.watch().listen((signal) {
    print(" caught ${++n} of 3");

    if (n == 3) {
      exit(0);
    }
  });
}
于 2020-10-04T02:38:04.677 回答