| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
type ExResult<T> = Result<T, Box<dyn std::error::Error + 'static>>; |
| 10 |
|
| 11 |
fn main() -> ExResult<()> { |
| 12 |
use caps::{CapSet, Capability}; |
| 13 |
|
| 14 |
|
| 15 |
println!("-> Current process priority is {}.", proc_nice()); |
| 16 |
let r = renice(19); |
| 17 |
assert_eq!(r, 0); |
| 18 |
println!("Lowered priority to +19."); |
| 19 |
println!("-> Current process priority is {}.", proc_nice()); |
| 20 |
|
| 21 |
|
| 22 |
let r = caps::drop(None, CapSet::Effective, Capability::CAP_SYS_NICE); |
| 23 |
assert!(r.is_ok()); |
| 24 |
println!("Dropped CAP_SYS_NICE."); |
| 25 |
let has_sys_nice = caps::has_cap(None, CapSet::Effective, Capability::CAP_SYS_NICE); |
| 26 |
assert!(has_sys_nice.is_ok()); |
| 27 |
assert_eq!(has_sys_nice.unwrap_or(true), false); |
| 28 |
let r = renice(-20); |
| 29 |
assert_eq!(r, -1); |
| 30 |
println!("Unprivileged, unable to raise priority to -20."); |
| 31 |
|
| 32 |
|
| 33 |
let perm_sys_nice = caps::has_cap(None, CapSet::Permitted, Capability::CAP_SYS_NICE); |
| 34 |
assert!(perm_sys_nice.is_ok()); |
| 35 |
if !perm_sys_nice? { |
| 36 |
return Err( |
| 37 |
"Try running this again as root/sudo or with CAP_SYS_NICE file capability!".into(), |
| 38 |
); |
| 39 |
} |
| 40 |
let r = caps::raise(None, CapSet::Effective, Capability::CAP_SYS_NICE); |
| 41 |
assert!(r.is_ok()); |
| 42 |
println!("Raised CAP_SYS_NICE."); |
| 43 |
|
| 44 |
|
| 45 |
let r = renice(-20); |
| 46 |
assert_eq!(r, 0); |
| 47 |
println!("Privileged, raised priority to -20."); |
| 48 |
println!("-> Current process priority is {}.", proc_nice()); |
| 49 |
|
| 50 |
Ok(()) |
| 51 |
} |
| 52 |
|
| 53 |
#[cfg(target_env = "musl")] |
| 54 |
const PRIO_PROCESS: i32 = libc::PRIO_PROCESS; |
| 55 |
#[cfg(not(target_env = "musl"))] |
| 56 |
const PRIO_PROCESS: u32 = libc::PRIO_PROCESS as u32; |
| 57 |
|
| 58 |
fn renice(prio: libc::c_int) -> libc::c_int { |
| 59 |
|
| 60 |
unsafe { libc::setpriority(PRIO_PROCESS, 0, prio) } |
| 61 |
} |
| 62 |
|
| 63 |
fn proc_nice() -> libc::c_int { |
| 64 |
|
| 65 |
let r = unsafe { libc::getpriority(PRIO_PROCESS as u32, 0) }; |
| 66 |
if r == -1 { |
| 67 |
panic!("getpriority failed."); |
| 68 |
} |
| 69 |
r |
| 70 |
} |