dartdart-io

How to catch SIGINT for the current in Dart?


How can Ctrl+C or SIGINT be caught in a Dart program for the current process?

Something similar to this for Node:

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

Solution

  • It looks like the SIGUSR1 and SIGUSR2 fields used in the old answer are now deprecated. I got the following example working using the sigint field:

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