我正在尝试管道2个IO对象,我来自nodejs,我们可以做类似的事情:
const child_process = require('child_process')
const shell = child_process.spawn('/bin/sh')
shell.stdout.pipe(process.stdout)
shell.stdin.write('pwd\n')
shell.stdin.write('ls\n')
/* write all command i want */
我正在寻找与水晶相同的东西
对于当前示例,我知道我们可以编写
shell = Process.new("/bin/sh", input: Process::Redirect::Pipe, output: STDOUT, error: STDOUT)
shell.input << "ls\n"
shell.input << "pwd\n"
# all commands i want
但是由于某种原因将TCPSocket传递给Process.new输入/输出/错误不能很好地工作(如果您有时间Process and TCPSocket not close properly in crystal,请参见此处)
所以我正在寻找另一种看起来像这样的方式:
shell = Process.new("/bin/sh", input: Process::Redirect::Pipe, output: Process::Redirect::Pipe, Process::Redirect::Pipe)
shell.output.pipe(STDOUT) # not the crystal pipe but like the nodejs pipe
shell.input << "ls\n"
shell.input << "pwd\n"
# all commands i want
答案 0 :(得分:2)
您可以在协同程序中使用IO.copy
:
shell = Process.new("/bin/sh", input: :pipe, output: :pipe, error: :pipe)
spawn { IO.copy shell.output, STDOUT }
spawn { IO.copy shell.error, STDERR }
shell.input << "ls /\n"
shell.input << "pwd\n"
shell.wait