mem_darwin.go 1.5 KB

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