Add example, update notes, gofmt

This commit is contained in:
Dustin Spicuzza
2021-07-06 12:38:03 -04:00
parent 02a88a138e
commit 35350a120e
3 changed files with 59 additions and 3 deletions

View File

@@ -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'
}

View File

@@ -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)
}

View File

@@ -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 {