Class: ProcessShared::SharedMemory

Inherits:
FFI::Pointer
  • Object
show all
Includes:
WithSelf
Defined in:
lib/process_shared/shared_memory.rb

Overview

Memory block shared across processes. TODO: finalizer that closes…

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from WithSelf

#with_self

Constructor Details

#initialize(size) ⇒ SharedMemory

Returns a new instance of SharedMemory.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/process_shared/shared_memory.rb', line 16

def initialize(size)
  @size = case size
          when Symbol
            FFI.type_size(size)
          else
            size
          end

  name = "/ps-shm#{rand(10000)}"
  @fd = RT.shm_open(name,
                    LibC::O_CREAT | LibC::O_RDWR | LibC::O_EXCL,
                    0777)
  RT.shm_unlink(name)
  
  LibC.ftruncate(@fd, @size)
  @pointer = LibC.mmap(nil,
                       @size,
                       LibC::PROT_READ | LibC::PROT_WRITE,
                       LibC::MAP_SHARED,
                       @fd,
                       0)
  super(@pointer)
end

Instance Attribute Details

#fdObject (readonly)

Returns the value of attribute fd.



10
11
12
# File 'lib/process_shared/shared_memory.rb', line 10

def fd
  @fd
end

#sizeObject (readonly)

Returns the value of attribute size.



10
11
12
# File 'lib/process_shared/shared_memory.rb', line 10

def size
  @size
end

Class Method Details

.open(size, &block) ⇒ Object



12
13
14
# File 'lib/process_shared/shared_memory.rb', line 12

def self.open(size, &block)
  new(size).with_self(&block)
end

Instance Method Details

#closeObject



40
41
42
43
# File 'lib/process_shared/shared_memory.rb', line 40

def close
  LibC.munmap(@pointer, @size)
  LibC.close(@fd)
end