use std::io;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Raised {
pub from: libc::rlim_t,
pub to: libc::rlim_t,
}
pub fn raise_open_file_limit() -> io::Result<Raised> {
let mut limit = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) } != 0 {
return Err(io::Error::last_os_error());
}
let from = limit.rlim_cur;
let to = ceiling(limit.rlim_max)?;
if to <= from {
return Ok(Raised { from, to: from });
}
limit.rlim_cur = to;
if unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) } != 0 {
return Err(io::Error::last_os_error());
}
Ok(Raised { from, to })
}
#[cfg(target_vendor = "apple")]
fn ceiling(hard: libc::rlim_t) -> io::Result<libc::rlim_t> {
let mut per_process: libc::c_int = 0;
let mut size = std::mem::size_of::<libc::c_int>();
let found = unsafe {
libc::sysctlbyname(
c"kern.maxfilesperproc".as_ptr(),
(&mut per_process as *mut libc::c_int).cast(),
&mut size,
std::ptr::null_mut(),
0,
)
};
if found != 0 {
return Err(io::Error::last_os_error());
}
let per_process = libc::rlim_t::try_from(per_process)
.map_err(|_| io::Error::other(format!("kern.maxfilesperproc is {per_process}")))?;
Ok(hard.min(per_process))
}
#[cfg(not(target_vendor = "apple"))]
fn ceiling(hard: libc::rlim_t) -> io::Result<libc::rlim_t> {
Ok(hard)
}