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



403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
# File 'lib/helper.rb', line 403

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)
        next unless Narou::Worker.canceled?
        next unless Narou::WebWorker.canceled?
        Process.kill("KILL", pid)
        Process.detach(pid)
        break
      end
    end
    looper.join
    looper = nil
  end
  stdout.force_encoding(Encoding::UTF_8)
  stderr.force_encoding(Encoding::UTF_8)
  return [stdout, stderr, status]
rescue RuntimeError => e
  raise unless e.message.include?("interrupted")
  process_kill(_pid)
  raise Interrupt
rescue Interrupt
  process_kill(_pid)
  raise
ensure
  looper&.kill
end

.process_kill(pid) ⇒ Object



436
437
438
439
440
441
# File 'lib/helper.rb', line 436

def self.process_kill(pid)
  return unless pid
  Process.kill("KILL", pid)
  Process.detach(pid) # 死亡確認しないとゾンビ化する
rescue
end