We actually just had to handle this problem in Rails isolation testing. I posted about it some on my blog.
Basically, what you want to do is open a pipe in the parent and child, and have the child write to the pipe. Here's a simple way to run the contents of a block in a child process and get back the result:
def do_in_child
read, write = IO.pipe
pid = fork do
read.close
result = yield
Marshal.dump(result, write)
exit!(0) # skips exit handlers.
end
write.close
result = read.read
Process.wait(pid)
raise "child failed" if result.empty?
Marshal.load(result)
end
Then you could run:
do_in_child do
require "some_polluting_library"
SomePollutingLibrary.some_operation
end
Note that if you do a require in the child, you will not have access to that library in the parent, so you cannot return an object of that type using this method. However, you could return any type that's available in both.
Also note that a lot of the details here (read.close
, Process.wait2(pid)
) are mostly housekeeping details, so if you use this a lot you should probably move this out into a utility library that you can reuse.
Finally, note that this will not work on Windows or JRuby, since they don't support forking.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…