Skip to content

Commit

Permalink
review changes
Browse files Browse the repository at this point in the history
  • Loading branch information
devnexen committed Sep 25, 2021
1 parent 8a36554 commit 7732f81
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 13 deletions.
25 changes: 16 additions & 9 deletions src/sys/pthread.rs
Expand Up @@ -8,7 +8,7 @@ use crate::Result;
use crate::sys::signal::Signal;
use libc::{self, pthread_t};
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
use std::ffi::{CStr, CString};
use std::ffi::CString;

/// Identifies an individual thread.
pub type Pthread = pthread_t;
Expand Down Expand Up @@ -43,17 +43,24 @@ pub fn pthread_kill<T: Into<Option<Signal>>>(thread: Pthread, signal: T) -> Resu
///
/// On linux the name cannot exceed 16 length including null terminator
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
pub fn pthread_getname_np(thread: Pthread) -> Result<String> {
let mut name = [0u8; 16];
pub fn pthread_getname_np(thread: Pthread) -> Result<CString> {
let mut name: Vec<u8> = Vec::with_capacity(16);
unsafe { name.set_len(16); }
unsafe { libc::pthread_getname_np(thread, name.as_mut_ptr() as _, name.len()) };
let cname = unsafe { CStr::from_ptr(name.as_ptr() as _) };
Ok(cname.to_owned().to_string_lossy().to_string())
let zi = name.iter().position(|x| *x == b'\0').unwrap();
name.truncate(zi);
Ok(unsafe { CString::from_vec_unchecked(name) })
}

/// Set the name of the thread
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
pub fn pthread_setname_np(thread: Pthread, name: String) {
let cname = CString::new(name).expect("name failed");
let nameptr = cname.as_ptr();
unsafe { libc::pthread_setname_np(thread, nameptr) };
pub fn pthread_setname_np<T: Into<Vec<u8>>>(thread: Pthread, name: T) -> Result<()> {
match CString::new(name.into()) {
Ok(cname) => {
let nameptr = cname.as_ptr();
let res = unsafe { libc::pthread_setname_np(thread, nameptr) };
Errno::result(res).map(drop)
},
Err(_) => Ok(()),
}
}
11 changes: 7 additions & 4 deletions test/sys/test_pthread.rs
Expand Up @@ -25,8 +25,11 @@ fn test_pthread_kill_none() {
#[cfg(all(target_os = "linux", not(target_env = "musl")))]
fn test_pthread_name_np() {
let tid = pthread_self();
let name = String::from("nix-rust");
pthread_setname_np(tid, name.clone());
let ret = pthread_getname_np(tid).unwrap();
assert!(name == ret);
let name = b"nix-rust";
let namestr = std::str::from_utf8(name).unwrap();
pthread_setname_np(tid, name.to_vec()).expect("Should pass");
let ret = pthread_getname_np(tid).expect("Should pass");
let retstr = ret.to_str().unwrap();

assert!(namestr == retstr);
}

0 comments on commit 7732f81

Please sign in to comment.