lowprio_unix.go 988 B

123456789101112131415161718192021222324252627282930313233343536
  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. "fmt"
  11. "syscall"
  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. if err := syscall.Setpriority(syscall.PRIO_PROCESS, pidSelf, wantNiceLevel); err != nil {
  27. return fmt.Errorf("set niceness: %w", err)
  28. }
  29. return nil
  30. }