/
notify.go
86 lines (80 loc) · 1.81 KB
/
notify.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package gotrig
import (
"io/ioutil"
"os"
"os/signal"
"path/filepath"
"sync"
"syscall"
)
/*
#include "skarnet.h"
*/
import "C"
func notifyNosig(path, s string) (int, error) {
files, err := ioutil.ReadDir(path)
if err != nil {
return 0, err
}
success := 0
for i := range files {
if files[i].Mode()&os.ModeNamedPipe == 0 {
continue
}
p := filepath.Join(path, files[i].Name())
fd, ferr := C.open_write(C.CString(p))
if fd == -1 {
if errno, ok := ferr.(syscall.Errno); ok && errno == syscall.ENXIO {
err = errno
os.Remove(p)
}
} else {
r, ferr := C.fd_write(fd, C.CString(s), C.uint(len(s)))
if (r < 0) || uint(r) < uint(len(s)) {
if errno, ok := ferr.(syscall.Errno); ok && errno == syscall.EPIPE {
err = errno
os.Remove(p)
}
// what to do if EGAIN ? full fifo -> fix the reader !
// There's a race condition in extreme cases though ;
// but it's still better to be nonblocking - the writer
// shouldn't get in trouble because of a bad reader.
C.fd_close(fd)
} else {
C.fd_close(fd)
success++
}
}
}
return success, err
}
func Clean(path string) error {
files, err := ioutil.ReadDir(path)
if err != nil {
return nil // yes, we don't care if the dir failed to scan
}
for i := range files {
if files[i].Mode()&os.ModeNamedPipe == 0 {
continue
}
p := filepath.Join(path, files[i].Name())
fd, ferr := C.open_write(C.CString(p))
if fd >= 0 {
C.fd_close(fd)
} else if errno, ok := ferr.(syscall.Errno); ok && errno == syscall.ENXIO {
err = os.Remove(p)
}
}
return err
}
// guard signal management
var notifyLock sync.Mutex
func Notify(path, s string) (int, error) {
notifyLock.Lock()
signal.Ignore(syscall.SIGPIPE)
defer func() {
signal.Reset(syscall.SIGPIPE)
notifyLock.Unlock()
}()
return notifyNosig(path, s)
}