...
1
2
3
4
5
6
7
8
9
10 package unix_test
11
12 import (
13 "fmt"
14 "os"
15 "path/filepath"
16 "testing"
17
18 "golang.org/x/sys/unix"
19 )
20
21 func TestMmap(t *testing.T) {
22 tmpdir := filepath.Join(t.TempDir(), "testdata")
23 if err := os.Mkdir(tmpdir, 0700); err != nil {
24 t.Fatal(err)
25 }
26 filename := filepath.Join(tmpdir, "memmapped_file")
27 destination, err := os.Create(filename)
28 if err != nil {
29 t.Fatal("os.Create:", err)
30 return
31 }
32
33 fmt.Fprintf(destination, "%s\n", "0 <- Flipped between 0 and 1 when test runs successfully")
34 fmt.Fprintf(destination, "%s\n", "//Do not change contents - mmap test relies on this")
35 destination.Close()
36 fd, err := unix.Open(filename, unix.O_RDWR, 0777)
37 if err != nil {
38 t.Fatalf("Open: %v", err)
39 }
40
41 b, err := unix.Mmap(fd, 0, 8, unix.PROT_READ, unix.MAP_SHARED)
42 if err != nil {
43 t.Fatalf("Mmap: %v", err)
44 }
45
46 if err := unix.Mprotect(b, unix.PROT_READ|unix.PROT_WRITE); err != nil {
47 t.Fatalf("Mprotect: %v", err)
48 }
49
50
51 flagWasZero := true
52 if b[0] == '0' {
53 b[0] = '1'
54 } else if b[0] == '1' {
55 b[0] = '0'
56 flagWasZero = false
57 }
58
59 if err := unix.Msync(b, unix.MS_SYNC); err != nil {
60 t.Fatalf("Msync: %v", err)
61 }
62
63
64 buf, err := os.ReadFile(filename)
65 if err != nil {
66 t.Fatalf("Could not read mmapped file from disc for test: %v", err)
67 }
68 if flagWasZero && buf[0] != '1' || !flagWasZero && buf[0] != '0' {
69 t.Error("Flag flip in MAP_SHARED mmapped file not visible")
70 }
71
72 if err := unix.Munmap(b); err != nil {
73 t.Fatalf("Munmap: %v", err)
74 }
75 }
76
View as plain text