Skip to content

Instantly share code, notes, and snippets.

@janv
Created July 28, 2011 20:32
Show Gist options
  • Save janv/1112483 to your computer and use it in GitHub Desktop.
Save janv/1112483 to your computer and use it in GitHub Desktop.
Small sample program to illustrate process management in ruby
#!/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
@sree0962
Copy link

sree0962 commented Jan 8, 2013

hi dude

@sree0962
Copy link

sree0962 commented Jan 8, 2013

i am writing a ruby code for scanning a web site.Can use the above code for purpose.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment