如何在Dart中捕获当前的SIGINT?

时间:2013-08-26 16:05:48

标签: dart dart-io

如何在当前进程的Dart程序中捕获 Ctrl + C 或SIGINT?

与Node类似的东西:

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

2 个答案:

答案 0 :(得分:5)

我在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();
}

答案 1 :(得分:1)

看起来旧答案中使用的SIGUSR1SIGUSR2字段现在为deprecated。我得到了使用sigint字段的以下示例:

import "dart:io";

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

    if (n == 3) {
      exit(0);
    }
  });
}