Skip to content

Commit 18c2038

Browse files
committed
Implement sched::sched_getaffinity()
sched_getaffinity(2) get a process's CPU affinity mask
1 parent 3c7a23b commit 18c2038

File tree

4 files changed

+114
-3
lines changed

4 files changed

+114
-3
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ This project adheres to [Semantic Versioning](http://semver.org/).
3030
- Added `linkat`
3131
([#1101](https://github.com/nix-rust/nix/pull/1101))
3232

33+
- Added `sched_getaffinity`.
34+
([#1148](https://github.com/nix-rust/nix/pull/1148))
35+
3336
### Changed
3437
- `sys::socket::recvfrom` now returns
3538
`Result<(usize, Option<SockAddr>)>` instead of `Result<(usize, SockAddr)>`.

src/sched.rs

Lines changed: 76 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,44 +46,82 @@ mod sched_linux_like {
4646

4747
pub type CloneCb<'a> = Box<dyn FnMut() -> isize + 'a>;
4848

49+
/// CpuSet represent a bit-mask of CPUs.
50+
/// CpuSets are used by sched_setaffinity and
51+
/// sched_getaffinity for example.
52+
///
53+
/// This is a wrapper around `libc::cpu_set_t`.
4954
#[repr(C)]
5055
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
5156
pub struct CpuSet {
5257
cpu_set: libc::cpu_set_t,
5358
}
5459

5560
impl CpuSet {
61+
/// Create a new and empty CpuSet.
5662
pub fn new() -> CpuSet {
5763
CpuSet {
5864
cpu_set: unsafe { mem::zeroed() },
5965
}
6066
}
6167

68+
/// Test to see if a CPU is in the CpuSet.
69+
/// `field` is the CPU id to test
6270
pub fn is_set(&self, field: usize) -> Result<bool> {
63-
if field >= 8 * mem::size_of::<libc::cpu_set_t>() {
71+
if field >= CpuSet::count() {
6472
Err(Error::Sys(Errno::EINVAL))
6573
} else {
6674
Ok(unsafe { libc::CPU_ISSET(field, &self.cpu_set) })
6775
}
6876
}
6977

78+
/// Add a CPU to CpuSet.
79+
/// `field` is the CPU id to add
7080
pub fn set(&mut self, field: usize) -> Result<()> {
71-
if field >= 8 * mem::size_of::<libc::cpu_set_t>() {
81+
if field >= CpuSet::count() {
7282
Err(Error::Sys(Errno::EINVAL))
7383
} else {
7484
Ok(unsafe { libc::CPU_SET(field, &mut self.cpu_set) })
7585
}
7686
}
7787

88+
/// Remove a CPU from CpuSet.
89+
/// `field` is the CPU id to remove
7890
pub fn unset(&mut self, field: usize) -> Result<()> {
79-
if field >= 8 * mem::size_of::<libc::cpu_set_t>() {
91+
if field >= CpuSet::count() {
8092
Err(Error::Sys(Errno::EINVAL))
8193
} else {
8294
Ok(unsafe { libc::CPU_CLR(field, &mut self.cpu_set) })
8395
}
8496
}
97+
98+
/// Return the maximum number of CPU in CpuSet
99+
pub fn count() -> usize {
100+
8 * mem::size_of::<libc::cpu_set_t>()
101+
}
85102
}
86103

104+
/// `sched_setaffinity` set a thread's CPU affinity mask
105+
/// ([`sched_setaffinity(2)`](http://man7.org/linux/man-pages/man2/sched_setaffinity.2.html))
106+
///
107+
/// `pid` is the thread ID to update.
108+
/// If pid is zero, then the calling thread is updated.
109+
///
110+
/// The `cpuset` argument specifies the set of CPUs on which the thread
111+
/// will be eligible to run.
112+
///
113+
/// # Example
114+
///
115+
/// Binding the current thread to CPU 0 can be done as follows:
116+
///
117+
/// ```rust,no_run
118+
/// use nix::sched::{CpuSet, sched_setaffinity};
119+
/// use nix::unistd::Pid;
120+
///
121+
/// let mut cpu_set = CpuSet::new();
122+
/// cpu_set.set(0);
123+
/// sched_setaffinity(Pid::from_raw(0), &cpu_set);
124+
/// ```
87125
pub fn sched_setaffinity(pid: Pid, cpuset: &CpuSet) -> Result<()> {
88126
let res = unsafe {
89127
libc::sched_setaffinity(
@@ -96,6 +134,41 @@ mod sched_linux_like {
96134
Errno::result(res).map(drop)
97135
}
98136

137+
/// `sched_getaffinity` get a thread's CPU affinity mask
138+
/// ([`sched_getaffinity(2)`](http://man7.org/linux/man-pages/man2/sched_getaffinity.2.html))
139+
///
140+
/// `pid` is the thread ID to check.
141+
/// If pid is zero, then the calling thread is checked.
142+
///
143+
/// Returned `cpuset` is the set of CPUs on which the thread
144+
/// is eligible to run.
145+
///
146+
/// # Example
147+
///
148+
/// Checking if the current thread can run on CPU 0 can be done as follows:
149+
///
150+
/// ```rust,no_run
151+
/// use nix::sched::sched_getaffinity;
152+
/// use nix::unistd::Pid;
153+
///
154+
/// let cpu_set = sched_getaffinity(Pid::from_raw(0)).unwrap();
155+
/// if cpu_set.is_set(0).unwrap() {
156+
/// println!("Current thread can run on CPU 0");
157+
/// }
158+
/// ```
159+
pub fn sched_getaffinity(pid: Pid) -> Result<CpuSet> {
160+
let mut cpuset = CpuSet::new();
161+
let res = unsafe {
162+
libc::sched_getaffinity(
163+
pid.into(),
164+
mem::size_of::<CpuSet>() as libc::size_t,
165+
&mut cpuset.cpu_set,
166+
)
167+
};
168+
169+
Errno::result(res).and(Ok(cpuset))
170+
}
171+
99172
pub fn clone(
100173
mut cb: CloneCb,
101174
stack: &mut [u8],

test/test.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,9 @@ mod test_net;
118118
mod test_nix_path;
119119
mod test_poll;
120120
mod test_pty;
121+
#[cfg(any(target_os = "android",
122+
target_os = "linux"))]
123+
mod test_sched;
121124
#[cfg(any(target_os = "android",
122125
target_os = "freebsd",
123126
target_os = "ios",

test/test_sched.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
use nix::sched::{sched_getaffinity, sched_setaffinity, CpuSet};
2+
use nix::unistd::Pid;
3+
4+
#[test]
5+
fn test_sched_affinity() {
6+
// If pid is zero, then the mask of the calling process is returned.
7+
let initial_affinity = sched_getaffinity(Pid::from_raw(0)).unwrap();
8+
let mut at_least_one_cpu = false;
9+
let mut last_valid_cpu = 0;
10+
for field in 0..CpuSet::count() {
11+
if initial_affinity.is_set(field).unwrap() {
12+
at_least_one_cpu = true;
13+
last_valid_cpu = field;
14+
}
15+
}
16+
assert!(at_least_one_cpu);
17+
18+
// Now restrict the running CPU
19+
let mut new_affinity = CpuSet::new();
20+
new_affinity.set(last_valid_cpu).unwrap();
21+
sched_setaffinity(Pid::from_raw(0), &new_affinity).unwrap();
22+
23+
// And now re-check the affinity which should be only the one we set.
24+
let updated_affinity = sched_getaffinity(Pid::from_raw(0)).unwrap();
25+
for field in 0..CpuSet::count() {
26+
// Should be set only for the CPU we set previously
27+
assert_eq!(updated_affinity.is_set(field).unwrap(), field==last_valid_cpu)
28+
}
29+
30+
// Finally, reset the initial CPU set
31+
sched_setaffinity(Pid::from_raw(0), &initial_affinity).unwrap();
32+
}

0 commit comments

Comments
 (0)