有没有办法管道IO?

Is there a way to pipe IO?

我正在尝试传输 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 */

我正在寻找在 crystal

中做同样的事情

我知道对于当前的例子我们可以写

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 input/output/error 效果不佳(如果您有时间,也请参阅此处

所以我正在寻找一种替代方式,看起来像:

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

您可以在协程中使用 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

https://carc.in/#/r/75z4