Wrapper around bash, control STDIN and STDOUT

可紊 提交于 2020-01-02 12:25:10

问题


I would like to talk to a interactive bash process.

Here is an example, so you know what I want to archieve:

  1. Program starts a new bash process.
  2. User types "ls" into my program.
  3. Program sends this command to the bash process.
  4. Program reads all available output of the bash (including the prompt) and displays it back to the user.
  5. GOTO 1

As you can guess, there is much room for nifty manipulations here and there... ;-)

It would be wonderful if this also worked for subprocesses (started by the bash process) and curses-based programs.

I would like to implement this functionality in Ruby, and already have experimented with IO.popen, but strange things happen. You are also welcome to do this in other languages.


回答1:


Ok, I've found a solution. This work pretty nicely, you can even start vim inside it :-)

require "pty"

system("stty raw -echo")

PTY.spawn("bash -i") do |pin, pout|
    Thread.new do
        loop do
            pout.print STDIN.getc.chr
        end
    end

    loop do
        print pin.sysread(512)
        STDOUT.flush
    end
end

This does the following:

  • enable character-wise input (limited to UNIXoids, I'm afraid)
  • create a pseudo-TTY, start a interactive bash session inside
  • forward each character from STDIN to the bash
  • print every output back to the user



回答2:


Have you tried using the Session gem?

  • http://rubygems.org/gems/session
  • https://github.com/ahoward/session (Homepage with introduction.)

I don't have any experience with it, but the README seems to describe what you want. It's description says, "session kicks the ass", so it should be fun/productive to play with it in any case.



来源:https://stackoverflow.com/questions/2730642/wrapper-around-bash-control-stdin-and-stdout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!