forked from siadat/ipc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
msgsnd_test.go
115 lines (102 loc) · 2.07 KB
/
msgsnd_test.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
115
package ipc_test
import (
"fmt"
"log"
"syscall"
"testing"
"time"
"github.com/siadat/ipc"
)
func TestMsgsnd(t *testing.T) {
keyFunc := func(path string, id uint) uint {
key, err := ipc.Ftok(path, id)
if err != nil {
t.Fatal(err)
}
return key
}
cases := []struct {
key uint
perm int
}{
{keyFunc("/dev/null", uint('m')), 0600},
}
for _, tt := range cases {
qid, err := ipc.Msgget(tt.key, ipc.IPC_CREAT|ipc.IPC_EXCL|tt.perm)
if err == syscall.EEXIST {
t.Errorf("queue(key=0x%x) exists", tt.key)
}
if err != nil {
t.Fatal(err)
}
defer func(qid uint) {
err := ipc.Msgctl(qid, ipc.IPC_RMID)
if err != nil {
t.Fatal(err)
}
}(qid)
mtext := "hello"
done := make(chan struct{})
go func() {
qbuf := &ipc.Msgbuf{Mtype: 12}
err := ipc.Msgrcv(qid, qbuf, 0)
if err != nil {
t.Fatal(err)
}
if want, got := mtext, string(qbuf.Mtext); want != got {
t.Fatalf("want %#v, got %#v", want, got)
}
fmt.Printf("Received: %s\n", string(qbuf.Mtext))
done <- struct{}{}
}()
m := &ipc.Msgbuf{Mtype: 12, Mtext: []byte(mtext)}
err = ipc.Msgsnd(qid, m, 0)
if err != nil {
t.Fatal(err)
}
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("blocked for too long")
}
}
}
func ExampleMsgsnd() {
// create an ftok key
key, err := ipc.Ftok("/dev/null", 42)
if err != nil {
panic(err)
}
// create a new message queue
qid, err := ipc.Msgget(key, ipc.IPC_CREAT|ipc.IPC_EXCL|0600)
if err == syscall.EEXIST {
log.Fatalf("queue(key=0x%x) exists", key)
}
if err != nil {
log.Fatal(err)
}
// remove queue in the end
defer func() {
err := ipc.Msgctl(qid, ipc.IPC_RMID)
if err != nil {
log.Fatal(err)
}
}()
// send a message
go func() {
msg := &ipc.Msgbuf{Mtype: 12, Mtext: []byte("bonjour")}
err = ipc.Msgsnd(qid, msg, 0)
if err != nil {
log.Fatal(err)
}
}()
// receive the message
msg := &ipc.Msgbuf{Mtype: 12}
err = ipc.Msgrcv(qid, msg, 0)
if err != nil {
log.Fatal(err)
}
fmt.Printf("received message: %q", msg.Mtext)
// Output:
// received message: "bonjour"
}