我正在创建一个脚本来包装 jdb(java 调试器)。我本质上想包装这个过程并代理用户交互。所以我希望它:
- 从我的脚本启动 jdb
- 将 jdb 的输出发送到 stdout
- 当 jdb 执行时暂停并等待输入
- 当用户输入命令时,将其传递给jdb
目前我真的想要一个通向 jdb 的 channel 。这样做的原因是使用特定参数初始化进程,并可能在将来添加更多命令。
更新: 这是使用expect最终为我工作的 shell :
PTY.spawn("jdb -attach 1234") do |read,write,pid|
write.sync = true
while (true) do
read.expect(/\r\r\n> /) do |s|
s = s[0].split(/\r\r\n/)
s.pop # get rid of prompt
s.each { |line| puts line }
print '> '
STDOUT.flush
write.print(STDIN.gets)
end
end
end
最佳答案
使用Open3.popen3()
。例如:
Open3.popen3("jdb args") { |stdin, stdout, stderr|
# stdin = jdb's input stream
# stdout = jdb's output stream
# stderr = jdb's stderr stream
threads = []
threads << Thread.new(stderr) do |terr|
while (line = terr.gets)
puts "stderr: #{line}"
end
end
threads << Thread.new(stdout) do |terr|
while (line = terr.gets)
puts "stdout: #{line}"
end
end
stdin.puts "blah"
threads.each{|t| t.join()} #in order to cleanup when you're done.
}
我已经给了您线程的示例,但是您当然希望对 jdb 正在做的事情做出响应。以上只是如何打开进程并处理与其通信的框架。
关于ruby - 如何在 ruby 中代理 shell 进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4839075/