我怀疑/the/program 在检测到 stdout 不是终端时正在缓冲 - 您可以通过 cat 管道进行测试,例如:
"/the/program" "argument" "argument" | cat
上面的答案,如果是问题就解决它,即:
#!/usr/bin/env ruby
require 'pty'
PTY.spawn "./the-program testing one Two three" do |r,w,p|
loop { puts "GOT: #{r.gets}" }
end
某些语言(例如 C)检测 stdout 是否为终端并更改为行缓冲 - 请参阅 Is stdout line buffered, unbuffered or indeterminate by default?
作为一个例子,我使用了一个简单的 bash 脚本来输出每个参数和时间,一次一个,中间间隔 3 秒,并且 ruby 脚本可以正常工作。我为这个例子添加了 eof 检测。
修改后的脚本:
#!/usr/bin/env ruby
process = IO.popen(["./the-program", "testing", "one", "Two", "three"])
while !process.eof?
line = process.gets
puts "GOT: #{line}"
end
节目内容:
#!/bin/bash
for arg
do
echo $arg
date
sleep 3
done
我尝试使用 ruby 版本 1.9.3 和 2.1.2
$ ruby ,p
GOT: testing
GOT: Mon Jun 16 06:19:00 EST 2014
GOT: one
GOT: Mon Jun 16 06:19:03 EST 2014
GOT: Two
GOT: Mon Jun 16 06:19:06 EST 2014
GOT: three
GOT: Mon Jun 16 06:19:09 EST 2014
$
如果我改用 C 程序,那么问题再次出现:
#include <stdio.h>
main(int argc, char **argv)
{
int i;
for (i=0; i<argc; i++) {
printf("%s\n", argv[i]);
sleep(3);
}
}