1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Copyright (c) 2021 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
// Use of this source is governed by Apache-2.0 License that can be found
// in the LICENSE file.

use crate::error::{Error, ErrorKind};

#[derive(Debug, Clone, Copy)]
pub enum IdType {
    /// Match PID.
    Pid,

    /// Match process group id.
    Group,

    /// match user UID.
    Uid,
}

/// Alter priority of running processes.
pub fn renice(id: i32, priority: i32, id_type: IdType) -> Result<(), Error> {
    if priority >= nc::PRIO_MAX || priority < nc::PRIO_MIN {
        return Err(Error::from_string(
            ErrorKind::ParameterError,
            format!(
                "Invalid priority {}, shall be in range {} ~ {}",
                priority,
                nc::PRIO_MIN,
                nc::PRIO_MAX
            ),
        ));
    }
    match id_type {
        IdType::Pid => nc::setpriority(nc::PRIO_PROCESS, id, priority).map_err(Into::into),
        IdType::Group => nc::setpriority(nc::PRIO_PGRP, id, priority).map_err(Into::into),
        IdType::Uid => nc::setpriority(nc::PRIO_USER, id, priority).map_err(Into::into),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_renice() {
        let ret = renice(nc::getpid(), 1, IdType::Pid);
        assert!(ret.is_ok());
    }
}