如何将数据发送到流程?

时间:2012-08-11 01:51:17

标签: process outputstream dart

我正在尝试编写一个dart服务器应用程序,它将与接受输入并提供输出的应用程序进行通信,如unix工具bc。

我可以读取bc的输出,但我无法向bc发送命令。这是我的代码:

#import('dart:io');

void main() {
  var p = Process.start('bc', ["-i"]);
  var stdoutStream = new StringInputStream(p.stdout);

  stdoutStream.onLine = () => print(stdoutStream.readLine());
  p.stdin.writeString("quit\n");

  p.onExit = (exitCode) {
    print('exit code: $exitCode');
    p.close();
  };
}

当我运行它时,我收到以下错误:

Unhandled exception:
SocketIOException: writeList failed - invalid socket handle
 0. Function: '_Socket@14117cc4.writeList' url: 'dart:io' line:4808 col:48
 1. Function: '_SocketOutputStream@14117cc4._write@14117cc4' url: 'dart:io' line:4993 col:70
 2. Function: '_SocketOutputStream@14117cc4.write' url: 'dart:io' line:4969 col:29
 3. Function: '_BaseOutputStream@14117cc4.writeString' url: 'dart:io' line:5197 col:3
 4. Function: '::main' url: 'file:///var/www/html/example.dart' line:8 col:22

如果我注释掉我尝试写“退出\ n”的行,那么它就会运行,我可以看到bc的输出。

那么如何让我的程序向我的服务器上的应用程序发送命令,如bc?

1 个答案:

答案 0 :(得分:3)

问题是你在进程正确启动之前写入stdin。尝试:

#import('dart:io');

void main() {
  var p = Process.start('bc', ["-i"]);
  var stdoutStream = new StringInputStream(p.stdout);

  stdoutStream.onLine = () => print(stdoutStream.readLine());
  p.onStart = () => p.stdin.writeString("1+1\nquit\n");

  p.onExit = (exitCode) {
    print('exit code: $exitCode');
    p.close();
  };
}