mem_darwin.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //go:build darwin
  2. // +build darwin
  3. package mem
  4. import (
  5. "context"
  6. "fmt"
  7. "unsafe"
  8. "github.com/shirou/gopsutil/v3/internal/common"
  9. "golang.org/x/sys/unix"
  10. )
  11. func getHwMemsize() (uint64, error) {
  12. total, err := unix.SysctlUint64("hw.memsize")
  13. if err != nil {
  14. return 0, err
  15. }
  16. return total, nil
  17. }
  18. // xsw_usage in sys/sysctl.h
  19. type swapUsage struct {
  20. Total uint64
  21. Avail uint64
  22. Used uint64
  23. Pagesize int32
  24. Encrypted bool
  25. }
  26. // SwapMemory returns swapinfo.
  27. func SwapMemory() (*SwapMemoryStat, error) {
  28. return SwapMemoryWithContext(context.Background())
  29. }
  30. func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) {
  31. // https://github.com/yanllearnn/go-osstat/blob/ae8a279d26f52ec946a03698c7f50a26cfb427e3/memory/memory_darwin.go
  32. var ret *SwapMemoryStat
  33. value, err := unix.SysctlRaw("vm.swapusage")
  34. if err != nil {
  35. return ret, err
  36. }
  37. if len(value) != 32 {
  38. return ret, fmt.Errorf("unexpected output of sysctl vm.swapusage: %v (len: %d)", value, len(value))
  39. }
  40. swap := (*swapUsage)(unsafe.Pointer(&value[0]))
  41. u := float64(0)
  42. if swap.Total != 0 {
  43. u = ((float64(swap.Total) - float64(swap.Avail)) / float64(swap.Total)) * 100.0
  44. }
  45. ret = &SwapMemoryStat{
  46. Total: swap.Total,
  47. Used: swap.Used,
  48. Free: swap.Avail,
  49. UsedPercent: u,
  50. }
  51. return ret, nil
  52. }
  53. func SwapDevices() ([]*SwapDevice, error) {
  54. return SwapDevicesWithContext(context.Background())
  55. }
  56. func SwapDevicesWithContext(ctx context.Context) ([]*SwapDevice, error) {
  57. return nil, common.ErrNotImplementedError
  58. }