-
-
Save fogus/1216434 to your computer and use it in GitHub Desktop.
Small sample program to illustrate process management in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'set' | |
class Monitor | |
@@max_procs = 3 | |
def initialize(worker_class) | |
@worker = worker_class.new | |
@interrupted = false | |
@threads = [] | |
end | |
def run | |
trap("INT") { @interrupted = true } | |
puts "Monitor #{Process.pid} started" | |
@@max_procs.times do |thread_num| | |
puts "Starting Monitor Thread #{thread_num}" | |
thread = Thread.new do | |
Thread.current[:num] = thread_num | |
puts "Monitor #{current_thread_num} started" | |
while !@interrupted | |
puts "Monitor #{current_thread_num} new iteration" | |
pid = spawn_child | |
wait_child(pid) | |
end | |
puts "Monitor #{current_thread_num} stopped" | |
end | |
@threads << thread | |
end | |
while threads_remaining | |
sleep(0.1) | |
end | |
end | |
def threads_remaining | |
@threads.find {|t| t.status} | |
end | |
def current_thread_num | |
Thread.current[:num] | |
end | |
def wait_child(pid) | |
puts "Monitor #{current_thread_num} waiting for Worker #{pid}" | |
Process.wait(pid) | |
puts "Monitor #{current_thread_num} received exit from Worker #{pid}" | |
end | |
def spawn_child | |
if pid = Process.fork() | |
puts "Monitor #{current_thread_num} spawned Worker #{pid}" | |
return pid | |
else | |
puts "\t Worker (Monitor #{current_thread_num}) #{Process.pid} starting" | |
@worker.run | |
puts "\t Worker (Monitor #{current_thread_num}) #{Process.pid} exiting" | |
exit | |
end | |
end | |
end | |
class Worker | |
def rand_time | |
byte = 0 | |
File.open('/dev/random', 'r') do |f| | |
byte += f.getbyte | |
byte += f.getbyte | |
byte += f.getbyte | |
byte += f.getbyte | |
end | |
byte / 1000.0 | |
end | |
def run | |
puts "\t Worker #{Process.pid} started" | |
time = 3 * rand_time | |
puts "\t Worker #{Process.pid} sleeping #{time}" | |
sleep(time) | |
end | |
end | |
monitor = Monitor.new(Worker) | |
monitor.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment