UPDATE – Ruby has a pretty awesome way to track the exit status of a shell command

Well I have to eat humble pie regarding my last rant on Ruby’s lack of decent exit status shell method. It turns out Ruby has a far more sophisticated method of accomplish this, which somewhat blows out both PHP and Python out of the water. The answer lies with the Process core module, in particular the Process.fork and Process.spawn methods. The main difference between these two Process methods is that the Process.fork method will let you run Ruby code in separate child processes from the mother process, while the Process.spawn method will let you call an external application (think of exec) also have it run in a separate child process independent from the main process.


Process.spawn('ls')
pid, status = Process.wait2

puts “PID: #{pid.inspect}”
puts ‘——————–‘
puts “Exit status: #{status.exitstatus}”

Outputs:

alpha03:tests tony$ ruby exitstatus.rb
exitstatus.rb
PID: 520
--------------------
Exit status: 0

The thing that I really liked about both Process.fork and Process.spawn methods is that you can omit the Process.waitpid (for fork)/Process.waitpid2 (for spawn) and Ruby will just fork/spawn the process in the background without having to wait for it to finish. This is makes writing daemon Ruby scripts a breeze.
Example:

Process.spawn("arpspoof -i eth1 -t 192.168.1.1 192.168.108, :out => ['script-output.txt', "a+"], :err=> ['script-error.txt', "a+"])

In the above example, a spawned arpspoof process is created in the background and it’s activity is logged in either the script-output.txt or script-error.txt files, If for some reason you need to keep a track of the spawned process, you can call it via the Process.detach method.

 

Documentation of the Ruby Process module:
http://www.ruby-doc.org/core-1.9.3/Process.html

Leave a Reply

Your email address will not be published. Required fields are marked *