lowprio_unix.go 991 B

1234567891011121314151617181920212223242526272829303132333435
  1. // Copyright (C) 2018 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. //go:build (!windows && !linux) || android
  7. // +build !windows,!linux android
  8. package osutil
  9. import (
  10. "syscall"
  11. "github.com/pkg/errors"
  12. )
  13. // SetLowPriority lowers the process CPU scheduling priority, and possibly
  14. // I/O priority depending on the platform and OS.
  15. func SetLowPriority() error {
  16. // Process zero is "self", niceness value 9 is something between 0
  17. // (default) and 19 (worst priority).
  18. const (
  19. pidSelf = 0
  20. wantNiceLevel = 9
  21. )
  22. if cur, err := syscall.Getpriority(syscall.PRIO_PROCESS, pidSelf); err == nil && cur >= wantNiceLevel {
  23. // We're done here.
  24. return nil
  25. }
  26. err := syscall.Setpriority(syscall.PRIO_PROCESS, pidSelf, wantNiceLevel)
  27. return errors.Wrap(err, "set niceness") // wraps nil as nil
  28. }