From 7bdae6482fdfc38ee969f3a1b19efb47a09c733f Mon Sep 17 00:00:00 2001 From: Patrick Mahoney Date: Sat, 17 Dec 2011 10:31:09 -0600 Subject: [PATCH] Add finalizer to SharedMemory. --- lib/process_shared/shared_memory.rb | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/lib/process_shared/shared_memory.rb b/lib/process_shared/shared_memory.rb index 4e187d2..9830e93 100644 --- a/lib/process_shared/shared_memory.rb +++ b/lib/process_shared/shared_memory.rb @@ -13,6 +13,14 @@ module ProcessShared new(size).with_self(&block) end + def self.make_finalizer(addr, size, fd) + proc do + pointer = FFI::Pointer.new(addr) + LibC.munmap(pointer, size) + LibC.close(fd) + end + end + def initialize(size) @size = case size when Symbol @@ -34,12 +42,16 @@ module ProcessShared LibC::MAP_SHARED, @fd, 0) + + @finalize = self.class.make_finalizer(@pointer.address, @size, @fd) + ObjectSpace.define_finalizer(self, @finalize) + super(@pointer) end def close - LibC.munmap(@pointer, @size) - LibC.close(@fd) + ObjectSpace.undefine_finalizer(self) + @finalize.call end end end