Skip to content

Commit 03b5a03

Browse files
committed
Change get/set name to CStrings
1 parent c3a8f30 commit 03b5a03

File tree

2 files changed

+11
-12
lines changed

2 files changed

+11
-12
lines changed

src/sys/prctl.rs

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -138,24 +138,21 @@ pub fn get_pdeathsig() -> Result<Option<Signal>> {
138138
}
139139

140140
/// Set the name of the calling thread. Strings longer than 15 bytes will be truncated.
141-
pub fn set_name(name: &str) -> Result<()> {
142-
let name = CString::new(name.as_bytes()).unwrap();
143-
141+
pub fn set_name(name: &CStr) -> Result<()> {
144142
let res = unsafe { libc::prctl(libc::PR_SET_NAME, name.as_ptr(), 0, 0, 0) };
145143

146144
Errno::result(res).map(drop)
147145
}
148146

149147
/// Return the name of the calling thread
150-
pub fn get_name() -> Result<String> {
148+
pub fn get_name() -> Result<CString> {
151149
// Size of buffer determined by linux/sched.h TASK_COMM_LEN
152150
let buf = [0u8; 16];
153151

154152
let res = unsafe { libc::prctl(libc::PR_GET_NAME, &buf, 0, 0, 0) };
155153

156154
let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
157-
let cstr = CStr::from_bytes_with_nul(&buf[..=len]).map_err(|_| Errno::EINVAL)?;
158-
let name = cstr.to_str().map_err(|_| Errno::EINVAL)?;
155+
let name = CStr::from_bytes_with_nul(&buf[..=len]).map_err(|_| Errno::EINVAL)?;
159156

160157
Errno::result(res).map(|_| name.to_owned())
161158
}

test/sys/test_prctl.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
#[cfg(target_os = "linux")]
22
#[cfg(feature = "process")]
33
mod test_prctl {
4+
use std::ffi::CStr;
5+
46
use nix::sys::prctl;
57

68
#[cfg_attr(qemu, ignore)]
@@ -68,17 +70,17 @@ mod test_prctl {
6870
fn test_get_set_name() {
6971
let original = prctl::get_name().unwrap();
7072

71-
let long_name = String::from("0123456789abcdefghijklmn");
72-
prctl::set_name(&long_name).unwrap();
73+
let long_name = CStr::from_bytes_with_nul(b"0123456789abcdefghijklmn\0").unwrap();
74+
prctl::set_name(long_name).unwrap();
7375
let res = prctl::get_name().unwrap();
7476

7577
// name truncated by kernel to TASK_COMM_LEN
76-
assert_eq!(&long_name[..15], res);
78+
assert_eq!(&long_name.to_str().unwrap()[..15], res.to_str().unwrap());
7779

78-
let short_name = String::from("01234567");
79-
prctl::set_name(&short_name).unwrap();
80+
let short_name = CStr::from_bytes_with_nul(b"01234567\0").unwrap();
81+
prctl::set_name(short_name).unwrap();
8082
let res = prctl::get_name().unwrap();
81-
assert_eq!(short_name, res);
83+
assert_eq!(short_name.to_str().unwrap(), res.to_str().unwrap());
8284

8385
prctl::set_name(&original).unwrap();
8486
}

0 commit comments

Comments
 (0)