lowprio_windows.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. package osutil
  7. import (
  8. "syscall"
  9. "github.com/pkg/errors"
  10. )
  11. const (
  12. // https://msdn.microsoft.com/en-us/library/windows/desktop/ms686219(v=vs.85).aspx
  13. aboveNormalPriorityClass = 0x00008000
  14. belowNormalPriorityClass = 0x00004000
  15. highPriorityClass = 0x00000080
  16. idlePriorityClass = 0x00000040
  17. normalPriorityClass = 0x00000020
  18. processModeBackgroundBegin = 0x00100000
  19. processModeBackgroundEnd = 0x00200000
  20. realtimePriorityClass = 0x00000100
  21. )
  22. // SetLowPriority lowers the process CPU scheduling priority, and possibly
  23. // I/O priority depending on the platform and OS.
  24. func SetLowPriority() error {
  25. modkernel32 := syscall.NewLazyDLL("kernel32.dll")
  26. setPriorityClass := modkernel32.NewProc("SetPriorityClass")
  27. if err := setPriorityClass.Find(); err != nil {
  28. return errors.Wrap(err, "find proc")
  29. }
  30. handle, err := syscall.GetCurrentProcess()
  31. if err != nil {
  32. return errors.Wrap(err, "get process handler")
  33. }
  34. defer syscall.CloseHandle(handle)
  35. res, _, err := setPriorityClass.Call(uintptr(handle), belowNormalPriorityClass)
  36. if res != 0 {
  37. // "If the function succeeds, the return value is nonzero."
  38. return nil
  39. }
  40. return errors.Wrap(err, "set priority class") // wraps nil as nil
  41. }