#[cfg(unix)]
pub struct SilenceStdout {
saved_fd: i32,
}
#[cfg(unix)]
impl SilenceStdout {
#[must_use]
pub fn new() -> Option<Self> {
use std::io::Write;
let _ = std::io::stdout().flush();
unsafe {
let saved_fd = libc::dup(libc::STDOUT_FILENO);
if saved_fd < 0 {
return None;
}
let devnull = libc::open(c"/dev/null".as_ptr(), libc::O_WRONLY);
if devnull < 0 {
libc::close(saved_fd);
return None;
}
if libc::dup2(devnull, libc::STDOUT_FILENO) < 0 {
libc::close(devnull);
libc::close(saved_fd);
return None;
}
libc::close(devnull);
Some(Self { saved_fd })
}
}
}
#[cfg(unix)]
impl Drop for SilenceStdout {
fn drop(&mut self) {
use std::io::Write;
let _ = std::io::stdout().flush();
unsafe {
libc::dup2(self.saved_fd, libc::STDOUT_FILENO);
libc::close(self.saved_fd);
}
}
}
#[cfg(not(unix))]
pub struct SilenceStdout;
#[cfg(not(unix))]
impl SilenceStdout {
#[must_use]
pub fn new() -> Option<Self> {
Some(Self)
}
}
#[cfg(not(unix))]
impl Drop for SilenceStdout {
fn drop(&mut self) {}
}