Class: Runfile::ExecHandler
- Inherits:
-
Object
- Object
- Runfile::ExecHandler
- Includes:
- Singleton
- Defined in:
- lib/runfile/exec.rb
Overview
This class 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.
Instance Method Summary collapse
-
#after_run(&block) ⇒ Object
Set a block to be called after each run.
-
#before_run(&block) ⇒ Object
Set a block to be called before each run.
-
#run(cmd) ⇒ Object
Run a command, wait until it is done and continue.
-
#run!(cmd) ⇒ Object
Run a command, wait until it is done, then exit.
-
#run_bg(cmd, pid: nil, log: '/dev/null') ⇒ Object
Run a command in the background, optionally log to a log file and save the process ID in a pid file.
-
#stop_bg(pid) ⇒ Object
Stop a command started with ‘run_bg’.
Instance Method Details
#after_run(&block) ⇒ Object
Set a block to be called after each run
61 62 63 |
# File 'lib/runfile/exec.rb', line 61 def after_run(&block) @after_run_block = block end |
#before_run(&block) ⇒ Object
Set a block to be called before each run
56 57 58 |
# File 'lib/runfile/exec.rb', line 56 def before_run(&block) @before_run_block = block end |
#run(cmd) ⇒ Object
Run a command, wait until it is done and continue
13 14 15 16 17 18 19 |
# File 'lib/runfile/exec.rb', line 13 def run(cmd) cmd = @before_run_block.call(cmd) if @before_run_block return false unless cmd say "!txtgrn!> #{cmd}" unless Runfile.quiet system cmd @after_run_block.call(cmd) if @after_run_block end |
#run!(cmd) ⇒ Object
Run a command, wait until it is done, then exit
22 23 24 25 26 27 |
# File 'lib/runfile/exec.rb', line 22 def run!(cmd) cmd = @before_run_block.call(cmd) if @before_run_block return false unless cmd say "!txtgrn!> #{cmd}" unless Runfile.quiet exec cmd end |
#run_bg(cmd, pid: nil, log: '/dev/null') ⇒ Object
Run a command in the background, optionally log to a log file and save the process ID in a pid file
31 32 33 34 35 36 37 38 39 40 |
# File 'lib/runfile/exec.rb', line 31 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}" unless Runfile.quiet 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) ⇒ Object
Stop a command started with ‘run_bg’. Provide the name of he pid file you used in ‘run_bg’
44 45 46 47 48 49 50 51 52 53 |
# File 'lib/runfile/exec.rb', line 44 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." unless Runfile.quiet end end |