Exit status on cmd executed via popen()

G

Garance A Drosihn

Sometimes I write ruby scripts to filter the output of some
other command. So I write something like:

cmdout = IO.popen(somecmd, "r")
cmdout.each_line {|aline|
# Do Stuff...
}
cmdout.close

Is there any way to find out what the exit status was from
the command given to popen? It would be nice to have some
method that I could use like:

if cmdout.popen_exit_status != 0
# Do Error-processing stuff
end

which could be done after reading all the lines, but before
the call to 'close'.

Or do I need to do something more complicated than 'popen'
if I need to know the exit code from that command?
 
G

Gennady

Try variable $?, it holds the status of the last executed command. Works
for commands executed with 'system', I think it is valid for popen as well.

Gennady.
 
G

Garance A Drosihn

Try variable $?, it holds the status of the last executed
command. Works for commands executed with 'system', I think
it is valid for popen as well.

Interesting. In the code sequence of:

cmdout = IO.popen(somecmd, "r")
cmdout.each_line {|aline|
# Do Stuff...
}
cmdout.close

I had tried checking $? just before cmdout.close, and it had a
value of nil. However, checking it immediately *after* the
close, it does seem to have $? set to the desired value. As
long as I can depend on this, it will do the job very nicely.
Thanks!
 
G

Gennady

Garance said:
Interesting. In the code sequence of:

cmdout = IO.popen(somecmd, "r")
cmdout.each_line {|aline|
# Do Stuff...
}
cmdout.close

I had tried checking $? just before cmdout.close, and it had a
value of nil. However, checking it immediately *after* the
close, it does seem to have $? set to the desired value. As
long as I can depend on this, it will do the job very nicely.
Thanks!

I have implemented a method available through Kernel.launch. It allows
you to execute several commands connecting all of them in a pipeline. I
makes available each command's return status together with stderr
messages. The last command's stdout is also available. I haven't
released it, however if you are interested you can get it at

http://homepage.mac.com/bystr/Development/Ruby/launch.rb

It has a set of unit tests attached, so it should be easy to figure out
the usage. I am not sure if it works on Windows as it uses fork() and
Process.waitpid2()

I mentioned it on ruby-talk before, you may find some description there:
http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/72318

Gennady.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top