Class: Helper::AsyncCommand

Inherits:
Object
  • Object
show all
Defined in:
lib/helper.rb

Overview

外部コマンド実行中の待機ループの処理を書けるクラス

返り値:[標準出力のキャプチャ, 標準エラーのキャプチャ, Process::Status]

response = Helper::AsyncCommand.exec(“処理に時間がかかる外部コマンド”) do

print "*"

end if response.success?

puts "成功しました"

end

Class Method Summary collapse

Class Method Details

.exec(command, sleep_time = 0.5, &block) ⇒ Object



387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/helper.rb', line 387

def self.exec(command, sleep_time = 0.5, &block)
  looper = nil
  _pid = nil
  status, stdout, stderr = systemu(command) do |pid|
    _pid = pid
    looper = Thread.new(pid) do |pid|
      loop do
        block.call if block
        sleep(sleep_time)
        if Narou::Worker.canceled?
          Process.kill("KILL", pid)
          Process.detach(pid)
          break
        end
      end
    end
    looper.join
    looper = nil
  end
  stdout.force_encoding(Encoding::UTF_8)
  stderr.force_encoding(Encoding::UTF_8)
  return [stdout, stderr, status]
rescue Interrupt
  if _pid
    begin
      Process.kill("KILL", _pid)
      Process.detach(_pid)    # 死亡確認しないとゾンビ化する
    rescue
    end
  end
  raise
ensure
  looper.kill if looper
end