我正在使用IO.popen执行命令并捕获输出,如下所示:
process = IO.popen("sudo -u service_user -i start_service.sh") do |io| while line = io.gets line.chomp! process_log_line(line) end end
如何捕获* start_service.sh *的退出状态?
解决方法
您可以通过引用$来捕获通过IO.open()调用的命令的退出状态.只要您在块的末尾关闭了管道.
在上面的示例中,您将执行以下操作:
process = IO.popen("sudo -u service_user -i start_service.sh") do |io| while line = io.gets line.chomp! process_log_line(line) end io.close do_more_stuff if $?.to_i == 0 end
有关更多信息,请参见Ruby Core Library entry for IO.popen.