Re: Std. IO streams in Ruby

Frederick Cheung
2010-08-01T19:30:46Z

On Aug 1, 7:29 pm, Jatin Kumar
<li...-fsXkhYbjdPsEEoCn2XhGlw@public.gmane.org>
wrote:
> In my rails controller, I am doing the following :
>
> @output = `g++ j.cpp -o "prog" && ./prog`
>
> This gives the output in the @output variable which i can display in my
> view. But the above works only if the j.cpp is correct and doesn''t
> expect any user input. How can I use the stdin/stderr and stdout streams
> here so that :
>
> If the user has to give input, I open a dialog box on the view with a
> textfield where he/she can enter the input, and the program continues to
> execute.
> If there are any errors in the file, then I should be able to get the
> errors and display them to the user.
> I tried doing this :
>
> @output = `g++ j.cpp -o "prog" && ./prog| tee prog`
>
> This allows me to enter the user input at the server command prompt (the
> server log...i don''t know what do we call it), but I want it to be
> entered in a textfield in the view.
>
> In short, how can I get control of stdin, so that whenever the stdin
> waits for some user input, i get to know that it is waiting for the user
> input and then i can show the user a text field and get the user input
> to be passed in the stdin stream.
> Let me know if there''s a doubt in the question.

Well in a plain old ruby script IO.popen allows you to run a command
and gets you the command stdin/stdout (and open3/popen3 gets you
stderr too).

Controlling this interactively via a webapp is much more tricky. A
single http request only has a single response, so you''d have to break
this up across multiple requests. There''s no guarantee that the next
request from the user will go to the same rails instance, so figuring
out what do do with the IO objects connecting you to the command being
run is tricky enough.

One possible way out is to have some long running daemon process that
does that actual running of the command and have your rails actions
communicate with that. If just polling for whether the command is
waiting for input isn''t acceptable then you might need to look at
comet and that sort of thing. If you can restrict yourself to specific
browsers, the new html5 websockets stuff might be interesting too

Fred

> --
> Posted viahttp://www.ruby-forum.com/.