pkg.re/essentialkaos/ek@v12.36.0+incompatible/system/process/process_nice.go (about) 1 // +build linux 2 3 package process 4 5 // ////////////////////////////////////////////////////////////////////////////////// // 6 // // 7 // Copyright (c) 2021 ESSENTIAL KAOS // 8 // Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0> // 9 // // 10 // ////////////////////////////////////////////////////////////////////////////////// // 11 12 import ( 13 "syscall" 14 15 "pkg.re/essentialkaos/ek.v12/mathutil" 16 ) 17 18 // ////////////////////////////////////////////////////////////////////////////////// // 19 20 const ( 21 PRIO_CLASS_NONE = 0 22 PRIO_CLASS_REAL_TIME = 1 23 PRIO_CLASS_BEST_EFFORT = 2 24 PRIO_CLASS_IDLE = 3 25 ) 26 27 // ////////////////////////////////////////////////////////////////////////////////// // 28 29 // GetCPUPriority returns process CPU scheduling priority (PR, NI, error) 30 func GetCPUPriority(pid int) (int, int, error) { 31 pr, err := syscall.Getpriority(syscall.PRIO_PROCESS, pid) 32 33 if err != nil { 34 return 0, 0, err 35 } 36 37 ni := 20 - pr 38 39 return 20 + ni, ni, nil 40 } 41 42 // SetCPUPriority sets process CPU scheduling priority 43 func SetCPUPriority(pid, niceness int) error { 44 return syscall.Setpriority(syscall.PRIO_PROCESS, pid, niceness) 45 } 46 47 // GetIOPriority returns process IO scheduling priority (class, classdata, error) 48 func GetIOPriority(pid int) (int, int, error) { 49 v, _, errNo := syscall.Syscall( 50 syscall.SYS_IOPRIO_GET, uintptr(1), uintptr(pid), uintptr(0), 51 ) 52 53 if errNo != 0 { 54 return 0, 0, errNo 55 } 56 57 prio := int(v) 58 class := prio >> 13 59 classdata := prio & ((1 << 13) - 1) 60 61 return class, classdata, nil 62 } 63 64 // SetIOPriority sets process IO scheduling priority 65 func SetIOPriority(pid, class, classdata int) error { 66 class = mathutil.Between(class, 0, 3) 67 classdata = mathutil.Between(classdata, 0, 7) 68 prio := (class << 13) | classdata 69 70 _, _, errNo := syscall.Syscall( 71 syscall.SYS_IOPRIO_SET, uintptr(1), uintptr(pid), uintptr(prio), 72 ) 73 74 if errNo != 0 { 75 return errNo 76 } 77 78 return nil 79 }