forked from rkorkosz/go-linux-mq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmq.go
114 lines (96 loc) · 1.77 KB
/
mq.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package mq
import (
"context"
"time"
"unsafe"
"golang.org/x/sys/unix"
)
type Config struct {
Name string
MaxMsg int64
MsgSize int64
}
type MQ struct {
ptr uintptr
MsgSize int64
}
type mqOpenAttrs struct {
_ int64
MaxMsg int64
MsgSize int64
_ int64
}
func New(cfg Config) (*MQ, error) {
name, err := unix.BytePtrFromString(cfg.Name)
if err != nil {
return nil, err
}
mq, _, errno := unix.Syscall6(
unix.SYS_MQ_OPEN,
uintptr(unsafe.Pointer(name)),
unix.O_RDWR|unix.O_CREAT,
0o600,
uintptr(unsafe.Pointer(&mqOpenAttrs{
MaxMsg: cfg.MaxMsg,
MsgSize: cfg.MsgSize,
})),
0,
0,
)
if errno != 0 {
return nil, errno
}
return &MQ{ptr: mq, MsgSize: cfg.MsgSize}, nil
}
func (mq *MQ) Close() error {
return unix.Close(int(mq.ptr))
}
func (mq *MQ) Send(ctx context.Context, data []byte, priority int) error {
timeout, ok := ctx.Deadline()
if !ok {
// sending immediately
timeout = time.Now().Add(-1)
}
t, err := unix.TimeToTimespec(timeout)
if err != nil {
return err
}
_, _, errno := unix.Syscall6(
unix.SYS_MQ_TIMEDSEND,
mq.ptr,
uintptr(unsafe.Pointer(&data[0])),
uintptr(len(data)),
uintptr(priority),
uintptr(unsafe.Pointer(&t)),
0,
)
if errno != 0 {
return errno
}
return nil
}
func (mq *MQ) Receive(ctx context.Context, priority int) ([]byte, error) {
var tm uintptr
timeout, ok := ctx.Deadline()
if ok {
t, err := unix.TimeToTimespec(timeout)
if err != nil {
return nil, err
}
tm = uintptr(unsafe.Pointer(&t))
}
msgBuf := make([]byte, mq.MsgSize)
n, _, errno := unix.Syscall6(
unix.SYS_MQ_TIMEDRECEIVE,
mq.ptr,
uintptr(unsafe.Pointer(&msgBuf[0])),
uintptr(mq.MsgSize),
uintptr(priority),
tm,
0,
)
if errno != 0 {
return nil, errno
}
return msgBuf[:n], nil
}