From 8e9c9b9553990a95871cf36241ae04c9688e80e0 Mon Sep 17 00:00:00 2001 From: Audrius Butkevicius Date: Thu, 18 Jan 2018 17:03:24 +0000 Subject: [PATCH] lib/osutil: Fix priority lowering on Windows GitHub-Pull-Request: https://github.com/syncthing/syncthing/pull/4686 --- lib/osutil/lowprio_windows.go | 38 ++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/lib/osutil/lowprio_windows.go b/lib/osutil/lowprio_windows.go index 457932080..75609ec13 100644 --- a/lib/osutil/lowprio_windows.go +++ b/lib/osutil/lowprio_windows.go @@ -6,8 +6,44 @@ package osutil +import ( + "syscall" + + "github.com/pkg/errors" +) + +const ( + // https://msdn.microsoft.com/en-us/library/windows/desktop/ms686219(v=vs.85).aspx + aboveNormalPriorityClass = 0x00008000 + belowNormalPriorityClass = 0x00004000 + highPriorityClass = 0x00000080 + idlePriorityClass = 0x00000040 + normalPriorityClass = 0x00000020 + processModeBackgroundBegin = 0x00100000 + processModeBackgroundEnd = 0x00200000 + realtimePriorityClass = 0x00000100 +) + // SetLowPriority lowers the process CPU scheduling priority, and possibly // I/O priority depending on the platform and OS. func SetLowPriority() error { - return nil + modkernel32 := syscall.NewLazyDLL("kernel32.dll") + setPriorityClass := modkernel32.NewProc("SetPriorityClass") + + if err := setPriorityClass.Find(); err != nil { + return errors.Wrap(err, "find proc") + } + + handle, err := syscall.GetCurrentProcess() + if err != nil { + return errors.Wrap(err, "get process handler") + } + defer syscall.CloseHandle(handle) + + res, _, err := setPriorityClass.Call(uintptr(handle), belowNormalPriorityClass) + if res != 0 { + // "If the function succeeds, the return value is nonzero." + return nil + } + return errors.Wrap(err, "set priority class") // wraps nil as nil }