shell_rs/
renice.rs

1// Copyright (c) 2021 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
2// Use of this source is governed by Apache-2.0 License that can be found
3// in the LICENSE file.
4
5use crate::error::{Error, ErrorKind};
6
7#[derive(Debug, Clone, Copy)]
8pub enum IdType {
9    /// Match PID.
10    Pid,
11
12    /// Match process group id.
13    Group,
14
15    /// match user UID.
16    Uid,
17}
18
19/// Alter priority of running processes.
20pub fn renice(id: i32, priority: i32, id_type: IdType) -> Result<(), Error> {
21    if priority >= nc::PRIO_MAX || priority < nc::PRIO_MIN {
22        return Err(Error::from_string(
23            ErrorKind::ParameterError,
24            format!(
25                "Invalid priority {}, shall be in range {} ~ {}",
26                priority,
27                nc::PRIO_MIN,
28                nc::PRIO_MAX
29            ),
30        ));
31    }
32    match id_type {
33        IdType::Pid => unsafe {
34            nc::setpriority(nc::PRIO_PROCESS, id, priority).map_err(Into::into)
35        },
36        IdType::Group => unsafe {
37            nc::setpriority(nc::PRIO_PGRP, id, priority).map_err(Into::into)
38        },
39        IdType::Uid => unsafe { nc::setpriority(nc::PRIO_USER, id, priority).map_err(Into::into) },
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[test]
48    fn test_renice() {
49        let ret = renice(nc::getpid(), 1, IdType::Pid);
50        assert!(ret.is_ok());
51    }
52}