lowprio_unix.go 948 B

12345678910111213141516171819202122232425262728293031323334
  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. // +build !windows,!linux android
  7. package osutil
  8. import (
  9. "syscall"
  10. "github.com/pkg/errors"
  11. )
  12. // SetLowPriority lowers the process CPU scheduling priority, and possibly
  13. // I/O priority depending on the platform and OS.
  14. func SetLowPriority() error {
  15. // Process zero is "self", niceness value 9 is something between 0
  16. // (default) and 19 (worst priority).
  17. const (
  18. pidSelf = 0
  19. wantNiceLevel = 9
  20. )
  21. if cur, err := syscall.Getpriority(syscall.PRIO_PROCESS, pidSelf); err == nil && cur >= wantNiceLevel {
  22. // We're done here.
  23. return nil
  24. }
  25. err := syscall.Setpriority(syscall.PRIO_PROCESS, pidSelf, wantNiceLevel)
  26. return errors.Wrap(err, "set niceness") // wraps nil as nil
  27. }