If I do something like system('sudo mount … ') then I don’t really
get any error codes back to see what happened because I just get the
sudo return code here. Is there a way to do this like a library call
in ruby ?
El Martes, 27 de Octubre de 2009, Jedrin
escribió:> If I do something like system('sudo mount … ') then I don’t really
get any error codes back to see what happened because I just get the
sudo return code here. Is there a way to do this like a library call
in ruby ?
Use open4 (gem install open4):
require “open4”
pid, stdin, stdout, stderr = Open4::popen4(“sudo mount…”)
ignored, status = Process::waitpid2 pid
if status.to_i != 0
puts “Error: Command returned #{status.to_i}”"
end
You can also inspect the output and error output reading stdout and
stderr
(they are IO objects, no strings).
Jedrin wrote:
If I do something like system('sudo mount … ') then I don’t really
get any error codes back to see what happened because I just get the
sudo return code here.
I think you should get the exit status of the program which sudo ran:
$ cat xxx.sh
exit 123
$ irb --simple-prompt
%x{sudo ./xxx.sh}
=> “”$?
=> #<Process::Status: pid=28583,exited(123)>$?.exitstatus
=> 123
[Ubuntu Hardy, sudo 1.6.9p10-1ubuntu3.5]
Otherwise, I don’t know if there’s a way to call the mount API directly
from ruby.
Even if there was, remember that it wouldn’t work unless the ruby script
itself were running as root. That is: if you need ‘sudo’ to get root as
in your original example, then it’s always going to be in a separate
process.