Debian Codegraph @

third_party/rust/dbus/examples/rtkit.rs

raw
1 /* This example asks the rtkit service to make our thread realtime priority.
2 Rtkit puts a few limitations on us to let us become realtime, such as setting
3 RLIMIT_RTTIME correctly, hence the syscalls. */
4
5 extern crate dbus;
6 extern crate libc;
7
8 use std::cmp;
9
10 use dbus::{Connection, BusType, Props, MessageItem, Message};
11
12 fn item_as_i64(i: MessageItem) -> Result<i64, Box<std::error::Error>> {
13 match i {
14 MessageItem::Int32(i) => Ok(i as i64),
15 MessageItem::Int64(i) => Ok(i),
16 _ => Err(Box::from(&*format!("Property is not integer ({:?})", i)))
17 }
18 }
19
20 fn rtkit_set_realtime(c: &Connection, thread: u64, prio: u32) -> Result<(), ::dbus::Error> {
21 let mut m = Message::new_method_call("org.freedesktop.RealtimeKit1", "/org/freedesktop/RealtimeKit1",
22 "org.freedesktop.RealtimeKit1", "MakeThreadRealtime").unwrap();
23 m.append_items(&[thread.into(), prio.into()]);
24 let mut r = try!(c.send_with_reply_and_block(m, 10000));
25 r.as_result().map(|_| ())
26 }
27
28 fn make_realtime(prio: u32) -> Result<u32, Box<std::error::Error>> {
29 let c = try!(Connection::get_private(BusType::System));
30
31 let p = Props::new(&c, "org.freedesktop.RealtimeKit1", "/org/freedesktop/RealtimeKit1",
32 "org.freedesktop.RealtimeKit1", 10000);
33
34 // Make sure we don't fail by wanting too much
35 let max_prio = try!(item_as_i64(try!(p.get("MaxRealtimePriority")))) as u32;
36 let prio = cmp::min(prio, max_prio);
37
38 // Enforce RLIMIT_RTPRIO, also a must before asking rtkit for rtprio
39 let max_rttime = try!(item_as_i64(try!(p.get("RTTimeUSecMax")))) as u64;
40 let new_limit = libc::rlimit64 { rlim_cur: max_rttime, rlim_max: max_rttime };
41 let mut old_limit = new_limit;
42 if unsafe { libc::getrlimit64(libc::RLIMIT_RTTIME, &mut old_limit) } < 0 {
43 return Err(Box::from("getrlimit failed"));
44 }
45 if unsafe { libc::setrlimit64(libc::RLIMIT_RTTIME, &new_limit) } < 0 {
46 return Err(Box::from("setrlimit failed"));
47 }
48
49 // Finally, let's ask rtkit to make us realtime
50 let thread_id = unsafe { libc::syscall(libc::SYS_gettid) };
51 let r = rtkit_set_realtime(&c, thread_id as u64, prio);
52
53 if r.is_err() {
54 unsafe { libc::setrlimit64(libc::RLIMIT_RTTIME, &old_limit) };
55 }
56
57 try!(r);
58 Ok(prio)
59 }
60
61
62 fn main() {
63 match make_realtime(5) {
64 Ok(n) => println!("Got rtprio, level {}", n),
65 Err(e) => println!("No rtprio: {}", e),
66 }
67 }