gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/ipc/cgo/shm/shm_linux.go (about) 1 package shm 2 3 import ( 4 "os" 5 "syscall" 6 "unsafe" 7 ) 8 9 // #cgo LDFLAGS: -static 10 // #include <stdlib.h> 11 // #include <errno.h> 12 // #include <sys/mman.h> 13 // 14 // #define Errno errno 15 import "C" 16 17 type Shm struct { 18 name string 19 fd int 20 data []byte 21 } 22 23 func Open(name string, flag int, mode os.FileMode) (*Shm, error) { 24 cname := C.CString(name) 25 defer C.free(unsafe.Pointer(cname)) 26 fd := int(C.shm_open(cname, C.int(flag), C.mode_t(mode))) 27 if fd == -1 { 28 return nil, syscall.Errno(C.Errno) 29 } 30 return &Shm{ 31 name: name, 32 fd: fd, 33 }, nil 34 } 35 36 func (s *Shm) Truncate(length int64) error { 37 return syscall.Ftruncate(s.fd, length) 38 } 39 40 func (s *Shm) Mmap(offset int64, length int, prot int, flags int) error { 41 data, err := syscall.Mmap(s.fd, offset, length, prot, flags) 42 if err != nil { 43 return err 44 } 45 s.data = data 46 return err 47 } 48 49 func (s *Shm) Name() string { 50 return s.name 51 } 52 53 func (s *Shm) Fd() int { 54 return s.fd 55 } 56 57 func (s *Shm) Data() []byte { 58 return s.data 59 } 60 61 func (s *Shm) Munmap() error { 62 return syscall.Munmap(s.data) 63 } 64 65 func (s *Shm) Close() error { 66 return syscall.Close(s.fd) 67 } 68 69 func (s *Shm) Unlink() error { 70 cname := C.CString(s.name) 71 defer C.free(unsafe.Pointer(cname)) 72 if C.shm_unlink(cname) == -1 { 73 return syscall.Errno(C.Errno) 74 } 75 return nil 76 }