Signal your intentions

16 Aug 2021

image of traffic lights

Signals?

Unix by this point in 2021 has a rich half a centruy history. One of Unix's features that its terminal based shells and applications can make use of are

The Dart way

Luckily for use Dart command line developers, Dart programs gained support for listening to unix signals all the way back in 2013. The Dart API for listening to signals is typically easy by just listening to a normal Dart stream, though only thing you need to remember is that each signal is represented by its own instance as a static constant of the ProcessSignal class, so to listen to a for example the SIGINT signal looks like this:

// typically ctrl-c in shell will generate a sigint
ProcessSignal.sigint.watch().listen((signal) {
  print('sigint disconnecting');
  // do any required cleanup tasks 
  exit(0);
});

Unfortunately the DartVM reserves listening to many Unix process signals for itself, allowing Dart programs to only listen for:

Out of the signals that Dart makes available for us to listen to, the most common one we probably want to listen to is SIGINT, which I demonstrated above and which corresponds to user doing a CRTL-C in most termainals.

And that's really all there is to handling signals in your Dart CLI programs!


I hope this has been of help to you and if it has or you have any other handy tips to share, please let me know in the comments below or via Twitter.