到目前为止,我从未使用过 Thread,但我认为在这种情况下我必须依赖它。我想分别处理 cURL 命令行的标准输出和标准错误,因为我想将进度指示器(写入标准错误)中的回车换行:
require "open3"
cmd="curl -b cookie.txt #{url} -L -o -"
Open3.popen3(cmd) do |stdin, stdout, stderr, wait_thr|
pid = wait_thr.pid
# I have to process stdout and stderr at the same time but
#asyncronously, because stdout gives much more data then the stderr
#stream. I instantiate a Thread object for reading the stderr, otherwise
#"getc" would block the stdout processing loop.
c=nil
line=""
stdout.each_char do |b|
STDOUT.print b
if c==nil then
c=""
thr = Thread.new {
c=stderr.getc
if c=="\r" || c=="\n" then
STDERR.puts line
line=""
else
line<<c
end
c=nil
}
end
#if stderr still holds some output then I process it:
line=""
stderr.each_char do |c|
if c=="\r" || c=="\n" then
STDERR.puts line
line=""
else
line<<c
end
end
exit_status = wait_thr.value.exitstatus
STDERR.puts exit_status
end #popen3
我的问题是如何避免在处理标准输出(stdout.each_char)时在每个循环周期创建一个新的线程实例?我认为这很耗时,我想实例化一次,然后使用它的方法,如停止和运行等。