9

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.

Michael Mairegger
  • 6,833
  • 28
  • 41
samiy
  • 93
  • 3
  • possible duplicate of [How to catch SIGINT for the current in Dart?](http://stackoverflow.com/questions/18448306/how-to-catch-sigint-for-the-current-in-dart) – Günter Zöchbauer Mar 08 '14 at 17:59

2 Answers2

3

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?

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
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.

Abhishek
  • 6,912
  • 14
  • 59
  • 85
Chris Buckett
  • 13,738
  • 5
  • 39
  • 46
  • I've reached pretty much the same conclusion. Was hoping that in the host process I could define onExit, but doesn't appear to be so. – samiy Jan 18 '13 at 11:09
  • It might be worth raising a feature request on [http://dartbug.com](http://dartbug.com). – Chris Buckett Jan 18 '13 at 13:04
  • This is now being implemented. [Bug](https://code.google.com/p/dart/issues/detail?id=15188) – Greg Lowe Dec 18 '13 at 19:52