module RunfileExec

This module provides methods for easily and politely run shell commands through a Runfile action. It is mainly a convenient wrapper around ‘system` and `exec` and it also adds functions for running background tasks with ease.

Constants

VERSION

Public Class Methods

pid_dir() click to toggle source
# File lib/runfile-exec/extensions.rb, line 11
def self.pid_dir
  @@pid_dir
end
pid_dir=(dir) click to toggle source
# File lib/runfile-exec/extensions.rb, line 7
def self.pid_dir=(dir)
  @@pid_dir = dir
end

Public Instance Methods

after_run(&block) click to toggle source

Set a block to be called after each run

# File lib/runfile-exec/extensions.rb, line 64
def after_run(&block)
  @after_run_block = block
end
before_run(&block) click to toggle source

Set a block to be called before each run

# File lib/runfile-exec/extensions.rb, line 59
def before_run(&block)
  @before_run_block = block
end
run(cmd) click to toggle source

Run a command, wait until it is done and continue

# File lib/runfile-exec/extensions.rb, line 16
def run(cmd)
  cmd = @before_run_block.call(cmd) if @before_run_block
  return false unless cmd
  say "!txtgrn!> #{cmd}"
  system cmd
  @after_run_block.call(cmd) if @after_run_block
end
run!(cmd) click to toggle source

Run a command, wait until it is done, then exit

# File lib/runfile-exec/extensions.rb, line 25
def run!(cmd)
  cmd = @before_run_block.call(cmd) if @before_run_block
  return false unless cmd
  say "!txtgrn!> #{cmd}"
  exec cmd
end
run_bg(cmd, pid: nil, log: '/dev/null') click to toggle source

Run a command in the background, optionally log to a log file and save the process ID in a pid file

# File lib/runfile-exec/extensions.rb, line 34
def run_bg(cmd, pid: nil, log: '/dev/null')
  cmd = @before_run_block.call(cmd) if @before_run_block
  return false unless cmd
  full_cmd = "exec #{cmd} >#{log} 2>&1"
  say "!txtgrn!> #{full_cmd}"
  process = IO.popen "exec #{cmd} >#{log} 2>&1"
  File.write pidfile(pid), process.pid if pid
  @after_run_block.call(cmd) if @after_run_block
  return process.pid
end
stop_bg(pid) click to toggle source

Stop a command started with ‘run_bg’. Provide the name of he pid file you used in ‘run_bg’

# File lib/runfile-exec/extensions.rb, line 47
def stop_bg(pid)
  file = pidfile(pid)
  if File.exist? file
    pid = File.read file
    File.delete file
    run "kill -s TERM #{pid}"
  else
    say "!txtred!PID file not found."
  end
end

Private Instance Methods

pid_dir() click to toggle source
# File lib/runfile-exec/extensions.rb, line 70
def pid_dir
  defined?(@@pid_dir) ? @@pid_dir : nil
end
pidfile(pid) click to toggle source
# File lib/runfile-exec/extensions.rb, line 74
def pidfile(pid)
  pid_dir ? "#{pid_dir}/#{pid}.pid" : "#{pid}.pid"
end