Debian Codegraph @

unix/example_sysvshm_test.go

raw
1 // Copyright 2021 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 //go:build (darwin && !ios) || (linux && !android)
6
7 package unix_test
8
9 import (
10 "log"
11
12 "golang.org/x/sys/unix"
13 )
14
15 func ExampleSysvShmGet() {
16 // create shared memory region of 1024 bytes
17 id, err := unix.SysvShmGet(unix.IPC_PRIVATE, 1024, unix.IPC_CREAT|unix.IPC_EXCL|0o600)
18 if err != nil {
19 log.Fatal("sysv shm create failed:", err)
20 }
21
22 // warning: sysv shared memory segments persist even after a process
23 // is destroyed, so it's very important to explicitly delete it when you
24 // don't need it anymore.
25 defer func() {
26 _, err := unix.SysvShmCtl(id, unix.IPC_RMID, nil)
27 if err != nil {
28 log.Fatal(err)
29 }
30 }()
31
32 // to use a shared memory region you must attach to it
33 b, err := unix.SysvShmAttach(id, 0, 0)
34 if err != nil {
35 log.Fatal("sysv attach failed:", err)
36 }
37
38 // you should detach from the segment when finished with it. The byte
39 // slice is no longer valid after detaching
40 defer func() {
41 if err = unix.SysvShmDetach(b); err != nil {
42 log.Fatal("sysv detach failed:", err)
43 }
44 }()
45
46 // Changes to the contents of the byte slice are reflected in other
47 // mappings of the shared memory identifer in this and other processes
48 b[42] = 'h'
49 b[43] = 'i'
50 }