Write to stdout in another isolate cause exception

Viewed 27

Environment

  • Windows 10
  • Flutter 3.0.5
  • Dart 2.17.6

Here is the code

void main() async {
  var errorReceivePort = ReceivePort();
  errorReceivePort.listen((message) {
    writeLogOnMainIoslate('Background service error : ${message.toString()}');
  });
  await writeLogOnMainIoslate(
      'prepare to write something to stdout in main isolate');
  stdout.write('write something in main isolate');
  await writeLogOnMainIoslate('${stdout.hasTerminal}\r\n');
  await Isolate.spawn(f, Object(), onError: errorReceivePort.sendPort);
}

void f(Object o) async {
  await writeLogOnOtherIsolate(
      'prepare to write something to stdout in other isolate');
  try {
    stdout.write('some message in other isolate');
  } catch (error) {
    await writeLogOnOtherIsolate(error.toString());
  }
  await writeLogOnOtherIsolate('end of other isolate');
}

then I got an error from errorReceivePort

Background service error : [FileSystemException: writeFrom failed, path = '' (OS Error: 控制代碼無效。
, errno = 6), #0      _RandomAccessFile.writeFromSync (dart:io/file_impl.dart:873)
#1      _StdConsumer.addStream.<anonymous closure> (dart:io/stdio.dart)
#2      _RootZone.runUnaryGuarded (dart:async/zone.dart:1618)
#3      _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341)
#4      _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271)
#5      _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:774)
#6      _StreamController._add (dart:async/stream_controller.dart:648)
#7      _StreamController.add (dart:async/stream_controller.dart:596)
#8      _StreamSinkImpl.add (dart:io/io_sink.dart:136)
#9      _IOSinkImpl.write (dart:io/io_sink.dart:269)
#10     _StdSink.write (dart:io/stdio.dart:315)
#11     f (package:a/main.dart:40)

Even if when running a Flutter app, stdout has no terminal, I expect same behavior in any isolate

My questions are

  1. Why the try-catch does not work for this condition?
  2. Use stdout in main isolate works(at least no error), but not works for another isolate
0 Answers
Related