问题
I need the ability to start two processes from dart, read the input from the first process, manipulate the output in dart and then send the data to a second process.
Note: in this example I state two processes but in reality I may need to create a pipe line involving any number of processes.
The two process are likely to be long running (assume minutes) and the output must be available as the processes process the data (think tail -f).
To re-inforce the last point the process may output large amounts of data so the data can't be stored in memory hence the stream approach that I've attempted.
I've tried the following but I'm not experienced with streams so I'm not even certain if I'm on the right track.
https://dartpad.dev/3ad46c7e28c80f6735a9ee350091d509
回答1:
You can use Stream.pipe:
import 'dart:convert';
import 'dart:io';
void main() async {
var ls = await Process.start('ls', []);
var head = await Process.start('head', ['-1']);
ls.stdout
.transform(utf8.decoder)
.transform(const LineSplitter())
.map((line) => '1: $line\n')
.transform(utf8.encoder)
.pipe(head.stdin)
.catchError(
(e) {
// forget broken pipe after head process exit
},
test: (e) => e is SocketException && e.osError.message == 'Broken pipe',
);
await head.stdout.pipe(stdout);
}
来源:https://stackoverflow.com/questions/59746768/dart-how-to-pass-data-from-one-process-to-another-via-streams