diff --git a/unix/example_sysvshm_test.go b/unix/example_sysvshm_test.go new file mode 100644 index 00000000..8512eb59 --- /dev/null +++ b/unix/example_sysvshm_test.go @@ -0,0 +1,57 @@ +// Copyright 2021 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +//go:build (darwin && amd64) || linux +// +build darwin,amd64 linux + +package unix_test + +import ( + "log" + "runtime" + + "golang.org/x/sys/unix" +) + +func ExampleSysvShmGet() { + // sysv shared memory isn't implemented on Android + if runtime.GOOS == "android" { + return + } + + // create shared memory region of 1024 bytes + id, err := unix.SysvShmGet(unix.IPC_PRIVATE, 1024, unix.IPC_CREAT|unix.IPC_EXCL|0o600) + if err != nil { + log.Fatal("sysv shm create failed:", err) + } + + // warning: sysv shared memory segments persist even after after a process + // is destroyed, so it's very important to explicitly delete it when you + // don't need it anymore. + defer func() { + _, err := unix.SysvShmCtl(id, unix.IPC_RMID, nil) + if err != nil { + log.Fatal(err) + } + }() + + // to use a shared memory region you must attach to it + b, err := unix.SysvShmAttach(id, 0, 0) + if err != nil { + log.Fatal("sysv attach failed:", err) + } + + // you should detach from the segment when finished with it. The byte + // slice is no longer valid after detaching + defer func() { + if err = unix.SysvShmDetach(b); err != nil { + log.Fatal("sysv detach failed:", err) + } + }() + + // Changes to the contents of the byte slice are reflected in other + // mappings of the shared memory identifer in this and other processes + b[42] = 'h' + b[43] = 'i' +} diff --git a/unix/sysvshm_unix.go b/unix/sysvshm_unix.go index 2ddcf894..8794ebb2 100644 --- a/unix/sysvshm_unix.go +++ b/unix/sysvshm_unix.go @@ -42,8 +42,6 @@ func SysvShmAttach(id int, addr uintptr, flag int) ([]byte, error) { return b, nil } - - // SysvShmDetach unmaps the shared memory slice returned from SysvShmAttach. // // It is not safe to use the slice after calling this function. @@ -56,6 +54,7 @@ func SysvShmDetach(data []byte) error { } // SysvShmGet returns the Sysv shared memory identifier associated with key. +// If the IPC_CREAT flag is specified a new segment is created. func SysvShmGet(key, size, flag int) (id int, err error) { return shmget(key, size, flag) } diff --git a/unix/sysvshm_unix_test.go b/unix/sysvshm_unix_test.go index 35bb0ee8..61c7b8d6 100644 --- a/unix/sysvshm_unix_test.go +++ b/unix/sysvshm_unix_test.go @@ -23,7 +23,7 @@ func TestSysvSharedMemory(t *testing.T) { if err != unix.ENOSYS { t.Fatalf("expected android to fail, but it didn't") } - return + return } if err != nil {