Skip to content

Instantly share code, notes, and snippets.

@dylanPowers
Last active August 29, 2015 14:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dylanPowers/9af25e6c8f0b1e7bf512 to your computer and use it in GitHub Desktop.
Save dylanPowers/9af25e6c8f0b1e7bf512 to your computer and use it in GitHub Desktop.
Running a process interactively in Dart
library broadcasted_stdin;
import 'dart:async';
import 'dart:io' as io;
class InteractiveProcess {
Future<int> get whenExits => _whenExits;
final BroadcastedStdin _stdin;
Future<int> _whenExits;
/**
* This is the same as Process.start except it runs interactively with the
* user.
*/
InteractiveProcess(this._stdin, String executable,
List<String> arguments, {String workingDirectory}) {
Future<io.Process> process;
process = io.Process.start(executable, arguments,
workingDirectory: workingDirectory);
_whenExits = process.then(_enableProcessInteraction);
}
Future<int> _enableProcessInteraction(io.Process process) {
io.stdout.addStream(process.stdout);
io.stderr.addStream(process.stderr);
process.stdin.addStream(_stdin.stream);
return process.exitCode;
}
}
/**
* A [BroadcastedStdin] allows for stdin to be listened to multiple times. This
* solves the problem of wanting to pipe stdin to multiple processes.
*/
class BroadcastedStdin {
Stream<List<int>> get stream => _stdin;
static StreamSubscription _broadcastSubscript;
static BroadcastedStdin _instance;
Stream _stdin = io.stdin.asBroadcastStream(onListen: _onBroadcastListen);
factory BroadcastedStdin() {
if (_instance == null) {
_instance = new BroadcastedStdin._();
}
return _instance;
}
BroadcastedStdin._();
/**
* This will kill all instances of this listener. Call this when program
* execution needs to finished. Failing to call this will result in a program
* that will never end as it will be stuck waiting on user input.
*/
static void killAll() {
if (_broadcastSubscript != null) {
_broadcastSubscript.cancel();
}
}
static void _onBroadcastListen(StreamSubscription streamSubscript) {
_broadcastSubscript = streamSubscript;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment