Skip to content

Instantly share code, notes, and snippets.

@gderosa
Created October 22, 2010 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gderosa/640264 to your computer and use it in GitHub Desktop.
Save gderosa/640264 to your computer and use it in GitHub Desktop.
Spawn children and/or take other resources? Clean it all when out of scope!
# Use ObjectSpace.define_finalizer, as
# inspired by the Ruby std library (tmpfile.rb)
class C
def initialize
@child_pid = fork do
sleep 1000
end
Process.detach(@child_pid) if @child_pid
ObjectSpace.define_finalizer self, Killer.new(@child_pid)
end
def do_somthing
'hi!'
end
class Killer
def initialize(pid)
@pid = pid
end
# mimic a proc-like behavior (Walks Like A Duck)
def call(*args)
Process.kill('TERM', @pid)
end
end
end
# convenience method
class Array
def random_element
return self[rand(length)]
end
end
# everything may go wrong in real life
ALL_EXCEPTIONS =
ObjectSpace.each_object(Class).select{|x| x.ancestors.include? Exception}
ALL_SIGNALS =
Signal.list.keys
EXCEPTION_PROBABILTY = 0.025
SIGNAL_PROBABILITY = 0.025
def randomly_except
raise ALL_EXCEPTIONS.random_element, "(Randomly generated exception)" if
rand < EXCEPTION_PROBABILTY
end
def randomly_signal
Process.kill(ALL_SIGNALS.random_element, 0) if
rand < SIGNAL_PROBABILITY
end
# the test program
pool = []
while(sleep 0.5) do
pool << C.new # consume machine resources ;-)
randomly_except
randomly_signal
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment