github.com/leslie-fei/fastcache@v0.0.0-20240520092641-b7a9eb05711f/shm/shm_linux.go (about)

     1  package shm
     2  
     3  import (
     4  	"hash/crc32"
     5  	"syscall"
     6  )
     7  
     8  const (
     9  	shmCreate = 01000
    10  	shmAccess = 00600
    11  )
    12  
    13  func NewMemory(key string, bytes uint64, createIfNotExists bool) *Memory {
    14  	return &Memory{
    15  		createIfNotExists: createIfNotExists,
    16  		shmkey:            key,
    17  		bytes:             bytes,
    18  	}
    19  }
    20  
    21  func (m *Memory) Attach() error {
    22  	if m.basep != 0 {
    23  		return nil
    24  	}
    25  
    26  	if 0 == m.shmid {
    27  		k := uintptr(crc32.ChecksumIEEE([]byte(m.shmkey)))
    28  		s := uintptr(m.bytes)
    29  		a := shmAccess
    30  		if m.createIfNotExists {
    31  			a |= shmCreate
    32  		}
    33  
    34  		shmid, _, errno := syscall.Syscall(syscall.SYS_SHMGET, k, s, uintptr(a))
    35  		if errno != 0 {
    36  			return error(errno)
    37  		}
    38  
    39  		m.shmid = uint64(shmid)
    40  	}
    41  
    42  	basep, _, errno := syscall.Syscall(syscall.SYS_SHMAT, uintptr(m.shmid), 0, 0)
    43  	if errno != 0 {
    44  		return error(errno)
    45  	}
    46  
    47  	m.basep = uint64(basep)
    48  	return nil
    49  }
    50  
    51  func (m *Memory) Detach() (err error) {
    52  	if m.basep != 0 {
    53  		_, _, errno := syscall.Syscall(syscall.SYS_SHMDT, uintptr(m.basep), 0, 0)
    54  		m.basep = 0
    55  		if 0 != errno {
    56  			err = error(errno)
    57  		}
    58  	}
    59  	return
    60  }