bind_process/
bind_process.rs

1extern crate hwloc;
2extern crate libc;
3#[cfg(target_os = "windows")]
4extern crate winapi;
5#[cfg(target_os = "windows")]
6extern crate kernel32;
7
8use hwloc::{Topology, CPUBIND_PROCESS, TopologyObject, ObjectType};
9
10/// Example which binds an arbitrary process (in this example this very same one) to
11/// the last core.
12fn main() {
13    let mut topo = Topology::new();
14
15    // load the current pid through libc
16    let pid = get_pid();
17
18    println!("Binding Process with PID {:?}", pid);
19
20    // Grab last core and exctract its CpuSet
21    let mut cpuset = last_core(&mut topo).cpuset().unwrap();
22
23    // Get only one logical processor (in case the core is SMT/hyper-threaded).
24    cpuset.singlify();
25
26    println!("Before Bind: {:?}",
27             topo.get_cpubind_for_process(pid, CPUBIND_PROCESS)
28                 .unwrap());
29
30    // Last CPU Location for this PID (not implemented on all systems)
31    if let Some(l) = topo.get_cpu_location_for_process(pid, CPUBIND_PROCESS) {
32        println!("Last Known CPU Location: {:?}", l);
33    }
34
35    // Bind to one core.
36    topo.set_cpubind_for_process(pid, cpuset, CPUBIND_PROCESS)
37        .unwrap();
38
39    println!("After Bind: {:?}",
40             topo.get_cpubind_for_process(pid, CPUBIND_PROCESS)
41                 .unwrap());
42
43    // Last CPU Location for this PID (not implemented on all systems)
44    if let Some(l) = topo.get_cpu_location_for_process(pid, CPUBIND_PROCESS) {
45        println!("Last Known CPU Location: {:?}", l);
46    }
47}
48
49/// Find the last core
50fn last_core(topo: &mut Topology) -> &TopologyObject {
51    let core_depth = topo.depth_or_below_for_type(&ObjectType::Core).unwrap();
52    let all_cores = topo.objects_at_depth(core_depth);
53    all_cores.last().unwrap()
54}
55
56#[cfg(target_os = "windows")]
57fn get_pid() -> winapi::minwindef::DWORD {
58    unsafe { kernel32::GetCurrentProcessId() }
59}
60
61#[cfg(not(target_os = "windows"))]
62fn get_pid() -> libc::pid_t {
63    unsafe { libc::getpid() }
64}