gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/ipc/cgo/sem/named-sem_linux.go (about) 1 package sem 2 3 import ( 4 "os" 5 "syscall" 6 "time" 7 "unsafe" 8 ) 9 10 // #cgo LDFLAGS: -static 11 // #include <stdlib.h> 12 // #include <errno.h> 13 // #include <time.h> 14 // #include <semaphore.h> 15 // 16 // #define Errno errno 17 // 18 // sem_t *go_sem_open2(const char *name, int flag) { 19 // return sem_open(name, flag); 20 // } 21 // 22 // sem_t *go_sem_open4(const char *name, int flag, mode_t mode, unsigned int value) { 23 // return sem_open(name, flag, mode, value); 24 // } 25 import "C" 26 27 type NamedSem struct { 28 name string 29 sem *Sem 30 } 31 32 func Open(name string, flag int, mode os.FileMode, value uint) (NamedSem, error) { 33 cname := C.CString(name) 34 defer C.free(unsafe.Pointer(cname)) 35 sem := C.go_sem_open4(cname, C.int(flag), C.mode_t(mode), C.uint(value)) 36 if sem == C.SEM_FAILED { 37 return NamedSem{}, syscall.Errno(C.Errno) 38 } 39 return NamedSem{ 40 name: name, 41 sem: (*Sem)(unsafe.Pointer(sem)), 42 }, nil 43 } 44 45 func (s NamedSem) Name() string { 46 return s.name 47 } 48 49 func (s NamedSem) Sem() *Sem { 50 return s.sem 51 } 52 53 func (s NamedSem) Wait() error { 54 return s.sem.Wait() 55 } 56 57 func (s NamedSem) TimedWait(t time.Time) error { 58 return s.sem.TimedWait(t) 59 } 60 61 func (s NamedSem) TryWait() (ok bool, err error) { 62 return s.sem.TryWait() 63 } 64 65 func (s NamedSem) Post() error { 66 return s.sem.Post() 67 } 68 69 func (s NamedSem) GetValue() (int, error) { 70 return s.sem.GetValue() 71 } 72 73 func (s NamedSem) Close() error { 74 if C.sem_close(&s.sem.sem) == -1 { 75 return syscall.Errno(C.Errno) 76 } 77 return nil 78 } 79 80 func (s NamedSem) Unlink() error { 81 cname := C.CString(s.name) 82 defer C.free(unsafe.Pointer(cname)) 83 if C.sem_unlink(cname) == -1 { 84 return syscall.Errno(C.Errno) 85 } 86 return nil 87 }