#[cfg(target_os = "linux")]
unsafe extern "C" {
pub fn closefrom(__lowfd: i32);
}
#[cfg(target_os = "macos")]
fn closefrom_fallback(lowfd: i32) {
unsafe {
let mut maxfd = libc::sysconf(libc::_SC_OPEN_MAX);
if maxfd < 0 {
maxfd = 256; }
let mut fd = lowfd as libc::c_long;
while fd < maxfd {
libc::close(fd as i32);
fd += 1;
}
}
}
#[cfg(target_os = "macos")]
pub fn closefrom(lowfd: i32) {
unsafe {
let pid = libc::getpid();
let sz = libc::proc_pidinfo(pid, libc::PROC_PIDLISTFDS, 0, std::ptr::null_mut(), 0);
if sz == 0 {
return; }
if sz < 0 {
return closefrom_fallback(lowfd);
}
let fdinfo_buf = libc::malloc(sz as usize) as *mut libc::proc_fdinfo;
if fdinfo_buf.is_null() {
return closefrom_fallback(lowfd);
}
let r = libc::proc_pidinfo(pid, libc::PROC_PIDLISTFDS, 0, fdinfo_buf.cast(), sz);
if r < 0 || r > sz {
libc::free(fdinfo_buf.cast());
return closefrom_fallback(lowfd);
}
let count = r as usize / size_of::<libc::proc_fdinfo>();
for i in 0..count {
let fd = (*fdinfo_buf.add(i)).proc_fd;
if fd >= lowfd {
libc::close(fd);
}
}
libc::free(fdinfo_buf.cast());
}
}