renice: use clap for real

This commit is contained in:
Sylvestre Ledru 2024-01-26 19:41:03 +01:00
parent 0747ccf170
commit dc7f34cc9b

@ -11,28 +11,29 @@ use std::str::FromStr;
use uucore::{error::UResult, format_usage, help_about, help_usage};
const ABOUT: &str = help_about!("renice.md");
const USAGE: &str = help_usage!("renice.md");
use clap::{crate_version, Command};
use clap::{crate_version, Arg, Command};
#[uucore::main]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
let args: Vec<String> = env::args().collect();
let matches = uu_app().try_get_matches_from(args)?;
if args.len() != 3 {
eprintln!("Usage: renice <nice value> <pid>");
process::exit(1);
}
let nice_value = match matches.get_one::<i32>("nice_value") {
Some(number) => number,
_ => {
eprintln!("Invalid nice value");
process::exit(1);
}
};
let nice_value = i32::from_str(&args[1]).unwrap_or_else(|_| {
eprintln!("Invalid nice value");
process::exit(1);
});
let pid = match matches.get_one::<i32>("pid") {
Some(number) => number,
_ => {
eprintln!("Invalid PID");
process::exit(1);
}
};
let pid = i32::from_str(&args[2]).unwrap_or_else(|_| {
eprintln!("Invalid PID");
process::exit(1);
});
if unsafe { libc::setpriority(PRIO_PROCESS, pid.try_into().unwrap(), nice_value) } == -1 {
if unsafe { libc::setpriority(PRIO_PROCESS, (*pid).try_into().unwrap(), *nice_value) } == -1 {
eprintln!("Failed to set nice value: {}", Error::last_os_error());
process::exit(1);
}
@ -47,4 +48,18 @@ pub fn uu_app() -> Command {
.about(ABOUT)
.override_usage(format_usage(USAGE))
.infer_long_args(true)
.arg(
Arg::new("nice_value")
.value_name("NICE_VALUE")
.help("The new nice value for the process")
.required(true)
.index(1),
)
.arg(
Arg::new("pid")
.value_name("PID")
.help("The PID of the process")
.required(true)
.index(2),
)
}