Forum: Ruby Return code of process from IO

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Farrel L. (Guest)
on 2006-03-22 22:09
(Received via mailing list)
Hi folks,

I'm using IO.popen to communicate with an external process. At some
point the external process will exit either with a true or false
condition. It uses shell return codes (0 for true, 1 for false) to
indicate that this is happened. Is there a way to get the vale of this
return code from an IO object? Or will it be better to use Kernel.` or
suchlike. The $? system var doesn't seem to be updated using IO.

Farrel
Farrel L. (Guest)
on 2006-03-22 22:36
(Received via mailing list)
Just solved it. Just run Process.wait after the call to the IO.popen
and $? gets updated.
Shea M. (Guest)
on 2006-03-22 23:05
(Received via mailing list)
Farrel L. wrote:
> Just solved it. Just run Process.wait after the call to the IO.popen
> and $? gets updated.

This doesn't work in this case:

#!/usr/bin/ruby

Thread.new{
   IO.popen('ls non_existant_dir').each_line{|l| puts l}
   sleep 10
   Process.wait
   puts "exit status is #{$?}, should be non-zero"
}

sleep 5

Thread.new{
   IO.popen('dir').each_line{|l| puts l}
   Process.wait
   puts "exit status is #{$?}, should be 0"
}

sleep 15

exit 0


~S
Farrel L. (Guest)
on 2006-03-22 23:09
(Received via mailing list)
Yeah that can be a problem, but luckily I'm not using any threads so
it seems to be working...
Shea M. (Guest)
on 2006-03-22 23:13
(Received via mailing list)
Shea M. wrote:
>   sleep 10
> }
>
> sleep 15
>
> exit 0
>
>
> ~S

This should work in a mt env.

IO.popen('dir') { |p|
	p.each_line{ |l| puts l }
	puts "exitstatus is #{Process.waitpid(p.pid)}"
}
Shea M. (Guest)
on 2006-03-22 23:24
(Received via mailing list)
Shea M. wrote:
>>   IO.popen('ls non_existant_dir').each_line{|l| puts l}
>>   puts "exit status is #{$?}, should be 0"
>
> IO.popen('dir') { |p|
>     p.each_line{ |l| puts l }
>     puts "exitstatus is #{Process.waitpid(p.pid)}"
> }
that should be #{Process.waitpid2(p.pid)[1].exitstatus}
This topic is locked and can not be replied to.