sysvshm_unix.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. //go:build (darwin && !ios) || linux
  5. package unix
  6. import "unsafe"
  7. // SysvShmAttach attaches the Sysv shared memory segment associated with the
  8. // shared memory identifier id.
  9. func SysvShmAttach(id int, addr uintptr, flag int) ([]byte, error) {
  10. addr, errno := shmat(id, addr, flag)
  11. if errno != nil {
  12. return nil, errno
  13. }
  14. // Retrieve the size of the shared memory to enable slice creation
  15. var info SysvShmDesc
  16. _, err := SysvShmCtl(id, IPC_STAT, &info)
  17. if err != nil {
  18. // release the shared memory if we can't find the size
  19. // ignoring error from shmdt as there's nothing sensible to return here
  20. shmdt(addr)
  21. return nil, err
  22. }
  23. // Use unsafe to convert addr into a []byte.
  24. b := unsafe.Slice((*byte)(unsafe.Pointer(addr)), int(info.Segsz))
  25. return b, nil
  26. }
  27. // SysvShmDetach unmaps the shared memory slice returned from SysvShmAttach.
  28. //
  29. // It is not safe to use the slice after calling this function.
  30. func SysvShmDetach(data []byte) error {
  31. if len(data) == 0 {
  32. return EINVAL
  33. }
  34. return shmdt(uintptr(unsafe.Pointer(&data[0])))
  35. }
  36. // SysvShmGet returns the Sysv shared memory identifier associated with key.
  37. // If the IPC_CREAT flag is specified a new segment is created.
  38. func SysvShmGet(key, size, flag int) (id int, err error) {
  39. return shmget(key, size, flag)
  40. }