2011-01-29 17 views
2

我正在創建一個腳本來包裝jdb(java調試器)。我基本上想要包裝這個過程並代理用戶交互。所以,我希望它:如何在ruby中代理shell進程

  • 開始加多寶從我的腳本
  • 發送加多寶的輸出到stdout
  • 暫停,等待輸入時,加多寶確實
  • 當用戶輸入命令,把它傳遞給jdb

此刻我真的想要傳遞給jdb。其原因是使用特定參數初始化進程,並可能在將來添加更多命令。

更新: 這裏有什麼最後我用期待的工作殼:

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 

回答

0

Ruby標準庫包含expect,它是專爲這種類型的問題而設計的。有關更多信息,請參閱the documentation

+0

鏈接無效。 – defactodeity

+0

謝謝;我刪除了示例鏈接。如果您發現任何具有示例用法的當前網站,請告訴我。 –

4

使用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正在做的事情。以上僅僅是您打開流程並處理與之溝通的框架。