pkg.re/essentialkaos/ek.10@v12.41.0+incompatible/system/process/process_nice.go (about)

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