shell-rs 0.2.6

Rust reimplementation of common coreutils APIs
Documentation
// 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 => unsafe {
            nc::setpriority(nc::PRIO_PROCESS, id, priority).map_err(Into::into)
        },
        IdType::Group => unsafe {
            nc::setpriority(nc::PRIO_PGRP, id, priority).map_err(Into::into)
        },
        IdType::Uid => unsafe { 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());
    }
}