From: Deadolus Date: 2008-01-19T03:54:59+09:00 Subject: Re: Start a program, get it's output, then kill it. while "multithreading"... On 18 Jan., 11:56, Robert Klemme wrote: > 2008/1/18, Deadolus : > > > > > i'd like to program a gui for iperf (http://sourceforge.net/projects/ > > iperf), it should run under windows And *NIX and I'm using fox as my > > gui toolkit, I'll use some extra calculations to get the parameters, > > that's why I can't use an already existing gui for iperf. > > I already designed the gui and I'm now moving to connect the different > > widgets to it's functions. > > After you set all your parameters (size of packet, bandwith, > > time, ...) I want to press a button and it should start iperf and > > parallely read the it's output, so I can display some statistics > > (running time and, on server side, the packet loss, maybe more). > > So what should I program to do this? > > I read about multithreading, IO.popen would be perfect, but how can I > > kill iperf when I want to quit, before iperf ran out of time? > > I think threads could also work (especially because one can kill > > threads, if no longer used so the program would be terminated), but > > what do I do to start the iperf? > > First of all killing a thread won't help because the process is in no > way attached to a Ruby thread (btw, this would also be true if Ruby > was using native threads). > > You can however use a thread to read output from IO.popen. For > example, you could stuff lines into a Queue which is read from your UI > thread and displayed. Or whatever you want do do with it. > > About the killing I am not sure. With a quick check I did not find a > proper way to get the PID of the child process with IO.popen. If > there is no way you could use popen with "-" as command (i.e. start a > child process), have that writ out the current PID (in $$) to stdout > and exec the process you want to start. The parent would then have to > read the child PID first and remember it somewhere. > > Kind regards > > robert > > -- > use.inject do |as, often| as.you_can - without end I think I found the solution, this is a example script: io = IO.popen("ping google.ch") #open a new io thread = Thread.new(io) {while !io.closed? do Thread.current["line"] = io.readline end}#ALWAYS read current line of io i=0 #example code... while i<10 do puts thread["line"] puts thread.status #puts out "sleep", so it's running... i+=1 sleep(1) end io.close #close io thread.status #puts out "nil" so it's terminated Seems like you easily can close a io just by "close". At least it isn't in my ps aux list any more... But I just tested under linux so far, so I can't say if this also works under windows (I currently have some problems with my windows box). What do you think about this solution? If anyone has a better solution, I'm still interested....