Ctrl+c in dart console application

2020-07-10 09:32发布

问题:

Is there a way to catch CTRL+C in dart console application?

For example, press CTRL+C to send clean "closing" packet to web socket clients from server instead of just brutally closing the sockets.

回答1:

I've had a dig around, and I think that the answer, at the moment is no.

You can capture stdin, for example:

import 'dart:io';

void main() {
  stdin.onData = () => print(stdin.read());
}

but this does not respond to CTRL+C.

Elsewhere, process.dart (part of the dart:io library) defines various signals, such as SIGQUIT, and an onExit() callback, but this is used to control child processes rather than the host process.



回答2:

This is now available

I found the following test code at 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();
}

Hopefully this will be released soon.

See also How to catch SIGINT for the current in Dart?



标签: dart