github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/system/host/host_bsd.go (about)

     1  //go:build darwin
     2  
     3  package host
     4  
     5  import (
     6  	"context"
     7  	"sync/atomic"
     8  
     9  	"golang.org/x/sys/unix"
    10  )
    11  
    12  // cachedBootTime must be accessed via atomic.Load/StoreUint64
    13  var cachedBootTime uint64
    14  
    15  func BootTimeWithContext(ctx context.Context) (uint64, error) {
    16  	t := atomic.LoadUint64(&cachedBootTime)
    17  	if t != 0 {
    18  		return t, nil
    19  	}
    20  	tv, err := unix.SysctlTimeval("kern.boottime")
    21  	if err != nil {
    22  		return 0, err
    23  	}
    24  
    25  	atomic.StoreUint64(&cachedBootTime, uint64(tv.Sec))
    26  
    27  	return uint64(tv.Sec), nil
    28  }
    29  
    30  func UptimeWithContext(ctx context.Context) (uint64, error) {
    31  	boot, err := BootTimeWithContext(ctx)
    32  	if err != nil {
    33  		return 0, err
    34  	}
    35  	return timeSince(boot), nil
    36  }