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



341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/helper.rb', line 341

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