ruby - 如何在 ruby​​ 中代理 shell 进程

标签 ruby shell

我正在创建一个脚本来包装 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/

相关文章:

在 Linux 中创建简单的 Shell

ruby-on-rails - 如何使 select 查询在 rails 中相对更快?

ruby-on-rails - Bundle 无法在 Mac OSX 10.7 上安装 RMagick gem

ruby - 我如何在测试中模拟 %x?

linux - 预计无法在我的 Bash 脚本中运行

linux - 在 "expect"命令之后有没有办法到 "send"和 "interact"

ruby - 强制在 Ruby 中调用 Kernel::method_name

ruby-on-rails - 如果 ActiveRecord::Base#create 在 3.2.13 中已弃用,我该如何使用它?

Linux - 使用 CLI 程序执行命令

linux - 在多个 shell 上运行 bash 脚本