#![cfg(all(feature = "system", unix))]
use sinf::{system::ProcessesToUpdate, system::System};
fn count_open_descriptors() -> usize {
const CAP: libc::c_long = 1 << 16;
let limit = match unsafe { libc::sysconf(libc::_SC_OPEN_MAX) } {
n if n > 0 => n.min(CAP),
_ => CAP,
};
(0..limit as libc::c_int)
.filter(|&fd| unsafe { libc::fcntl(fd, libc::F_GETFD) } != -1)
.count()
}
#[cfg(target_os = "freebsd")]
fn describe_kernel_file_table() -> String {
let mib = [
libc::CTL_KERN,
libc::KERN_PROC,
libc::KERN_PROC_FILEDESC,
std::process::id() as libc::c_int,
];
let mut len: libc::size_t = 0;
let mut out = String::new();
unsafe {
if libc::sysctl(
mib.as_ptr(),
mib.len() as _,
std::ptr::null_mut(),
&mut len,
std::ptr::null_mut(),
0,
) != 0
{
return "kern.proc.filedesc: the size query failed".to_string();
}
len = len * 4 / 3;
let mut buf = vec![0u8; len];
if libc::sysctl(
mib.as_ptr(),
mib.len() as _,
buf.as_mut_ptr() as _,
&mut len,
std::ptr::null_mut(),
0,
) != 0
{
return "kern.proc.filedesc: the read failed".to_string();
}
let mut offset = 0;
while offset < len {
let record = buf.as_ptr().add(offset) as *const libc::kinfo_file;
let size = std::ptr::addr_of!((*record).kf_structsize).read_unaligned();
if size <= 0 {
break;
}
let fd = std::ptr::addr_of!((*record).kf_fd).read_unaligned();
let kind = std::ptr::addr_of!((*record).kf_type).read_unaligned();
let path = std::ffi::CStr::from_ptr(std::ptr::addr_of!((*record).kf_path) as _);
out.push_str(&format!(
" kf_fd={fd:>3} kf_type={kind} path={:?}\n",
path.to_string_lossy()
));
offset += size as usize;
}
}
out
}
#[cfg(not(target_os = "freebsd"))]
fn describe_kernel_file_table() -> String {
String::new()
}
#[test]
fn open_files_counts_the_open_descriptors() {
if cfg!(feature = "apple-sandbox") {
return;
}
let Ok(pid) = sinf::system::get_current_pid() else {
return;
};
let Ok(mut s) = System::new() else { return };
let probe = usize::from(cfg!(any(
target_os = "linux",
target_os = "android",
target_os = "netbsd"
)));
s.refresh_processes(ProcessesToUpdate::Some(&[pid]), false);
let expected = count_open_descriptors() + probe;
s.refresh_processes(ProcessesToUpdate::Some(&[pid]), false);
let Some(reported) = s.process(pid).and_then(|p| p.open_files()) else {
return;
};
assert_eq!(
reported,
expected,
"`open_files` differs from a direct count of the open descriptors\n{}",
describe_kernel_file_table(),
);
}