Class: Subexec

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

Overview

# Subexec

## Description

Subexec is a simple library that spawns an external command with an optional timeout parameter. It relies on Ruby 1.9’s Process.spawn method. Also, it works with synchronous and asynchronous code.

Useful for libraries that are Ruby wrappers for CLI’s. For example, resizing images with ImageMagick’s mogrify command sometimes stalls and never returns control back to the original process. Subexec executes mogrify and preempts if it gets lost.

## Usage

# Print hello sub = Subexec.run “echo ‘hello’ && sleep 3”, :timeout => 5 puts sub.output # returns: hello puts sub.exitstatus # returns: 0

# Timeout process after a second sub = Subexec.run “echo ‘hello’ && sleep 3”, :timeout => 1 puts sub.output # returns: puts sub.exitstatus # returns:

Constant Summary collapse

VERSION =
'0.2.3'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(command, options = {}) ⇒ Subexec

Returns a new instance of Subexec.



45
46
47
48
49
50
51
# File 'lib/subexec.rb', line 45

def initialize(command, options={})
  self.command    = command
  self.lang       = options[:lang]      || "C"
  self.timeout    = options[:timeout]   || -1     # default is to never timeout
  self.log_file   = options[:log_file]
  self.exitstatus = 0
end

Instance Attribute Details

#commandObject

Returns the value of attribute command.



31
32
33
# File 'lib/subexec.rb', line 31

def command
  @command
end

#exitstatusObject

Returns the value of attribute exitstatus.



31
32
33
# File 'lib/subexec.rb', line 31

def exitstatus
  @exitstatus
end

#langObject

Returns the value of attribute lang.



31
32
33
# File 'lib/subexec.rb', line 31

def lang
  @lang
end

#log_fileObject

Returns the value of attribute log_file.



31
32
33
# File 'lib/subexec.rb', line 31

def log_file
  @log_file
end

#outputObject

Returns the value of attribute output.



31
32
33
# File 'lib/subexec.rb', line 31

def output
  @output
end

#pidObject

Returns the value of attribute pid.



31
32
33
# File 'lib/subexec.rb', line 31

def pid
  @pid
end

#timeoutObject

Returns the value of attribute timeout.



31
32
33
# File 'lib/subexec.rb', line 31

def timeout
  @timeout
end

Class Method Details

.run(command, options = {}) ⇒ Object



39
40
41
42
43
# File 'lib/subexec.rb', line 39

def self.run(command, options={})
  sub = new(command, options)
  sub.run!
  sub
end

Instance Method Details

#run!Object



53
54
55
56
57
58
59
# File 'lib/subexec.rb', line 53

def run!
  if RUBY_VERSION >= '1.9' && RUBY_ENGINE != 'jruby'
    spawn
  else
    exec
  end
end