use std::io;
use std::os::raw::c_int;
#[cfg(unix)]
unsafe fn c_dup(fd: c_int) -> c_int {
unsafe extern "C" {
fn dup(fd: c_int) -> c_int;
}
unsafe { dup(fd) }
}
#[cfg(unix)]
unsafe fn c_dup2(src: c_int, dst: c_int) -> c_int {
unsafe extern "C" {
fn dup2(src: c_int, dst: c_int) -> c_int;
}
unsafe { dup2(src, dst) }
}
#[cfg(unix)]
unsafe fn c_close(fd: c_int) -> c_int {
unsafe extern "C" {
fn close(fd: c_int) -> c_int;
}
unsafe { close(fd) }
}
#[cfg(windows)]
unsafe fn c_dup(fd: c_int) -> c_int {
unsafe extern "C" {
fn _dup(fd: c_int) -> c_int;
}
unsafe { _dup(fd) }
}
#[cfg(windows)]
unsafe fn c_dup2(src: c_int, dst: c_int) -> c_int {
unsafe extern "C" {
fn _dup2(src: c_int, dst: c_int) -> c_int;
}
unsafe { _dup2(src, dst) }
}
#[cfg(windows)]
unsafe fn c_close(fd: c_int) -> c_int {
unsafe extern "C" {
fn _close(fd: c_int) -> c_int;
}
unsafe { _close(fd) }
}
#[inline]
pub unsafe fn sys_dup(fd: c_int) -> c_int {
unsafe { c_dup(fd) }
}
#[inline]
pub unsafe fn sys_dup2(src: c_int, dst: c_int) -> c_int {
unsafe { c_dup2(src, dst) }
}
#[inline]
pub unsafe fn sys_close(fd: c_int) -> c_int {
unsafe { c_close(fd) }
}
#[cfg(unix)]
pub fn get_file_fd(file: &std::fs::File) -> c_int {
use std::os::unix::io::AsRawFd;
file.as_raw_fd()
}
#[cfg(windows)]
pub fn get_file_fd(file: &std::fs::File) -> c_int {
use std::os::windows::io::AsRawHandle;
unsafe extern "C" {
fn _open_osfhandle(os_handle: isize, flags: c_int) -> c_int;
}
unsafe { _open_osfhandle(file.as_raw_handle() as isize, 0) }
}
#[cfg(not(any(unix, windows)))]
pub fn get_file_fd(_file: &std::fs::File) -> c_int {
-1
}
#[derive(Debug)]
pub struct FdRedirectGuard {
target_fd: c_int,
saved_fd: c_int,
active: bool,
}
impl FdRedirectGuard {
pub fn redirect_stdout_to(new_fd: c_int) -> io::Result<Self> {
Self::redirect(1, new_fd)
}
pub fn redirect_stderr_to(new_fd: c_int) -> io::Result<Self> {
Self::redirect(2, new_fd)
}
pub fn redirect(target_fd: c_int, new_fd: c_int) -> io::Result<Self> {
use std::io::Write;
if target_fd == 1 {
let _ = io::stdout().flush();
} else if target_fd == 2 {
let _ = io::stderr().flush();
}
let saved_fd = unsafe { sys_dup(target_fd) };
if saved_fd < 0 {
return Err(io::Error::last_os_error());
}
if unsafe { sys_dup2(new_fd, target_fd) } < 0 {
let err = io::Error::last_os_error();
unsafe { sys_close(saved_fd); }
return Err(err);
}
Ok(Self {
target_fd,
saved_fd,
active: true,
})
}
pub fn target_fd(&self) -> c_int {
self.target_fd
}
pub fn saved_fd(&self) -> c_int {
self.saved_fd
}
pub fn is_active(&self) -> bool {
self.active
}
pub fn restore(&mut self) -> io::Result<()> {
if !self.active {
return Ok(());
}
use std::io::Write;
if self.target_fd == 1 {
let _ = io::stdout().flush();
} else if self.target_fd == 2 {
let _ = io::stderr().flush();
}
self.active = false;
let res = unsafe { sys_dup2(self.saved_fd, self.target_fd) };
unsafe { sys_close(self.saved_fd); }
if res < 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
}
impl Drop for FdRedirectGuard {
fn drop(&mut self) {
let _ = self.restore();
}
}
pub fn run_command_with_timeout(
cmd: &mut std::process::Command,
timeout: std::time::Duration,
) -> Result<(std::process::ExitStatus, String, String), String> {
use std::io::Read;
use std::sync::{Arc, Mutex};
let mut child = cmd
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.map_err(|e| e.to_string())?;
let mut stdout = child.stdout.take().unwrap();
let mut stderr = child.stderr.take().unwrap();
let out_buf = Arc::new(Mutex::new(Vec::new()));
let err_buf = Arc::new(Mutex::new(Vec::new()));
let out_buf_clone = out_buf.clone();
let out_thread = std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = stdout.read_to_end(&mut buf);
*out_buf_clone.lock().unwrap() = buf;
});
let err_buf_clone = err_buf.clone();
let err_thread = std::thread::spawn(move || {
let mut buf = Vec::new();
let _ = stderr.read_to_end(&mut buf);
*err_buf_clone.lock().unwrap() = buf;
});
let start = std::time::Instant::now();
let mut status = None;
while start.elapsed() < timeout {
match child.try_wait() {
Ok(Some(s)) => {
status = Some(s);
break;
}
Ok(None) => {
std::thread::sleep(std::time::Duration::from_millis(5));
}
Err(e) => {
return Err(e.to_string());
}
}
}
if let Some(s) = status {
let _ = out_thread.join();
let _ = err_thread.join();
let stdout_bytes = Arc::try_unwrap(out_buf).unwrap().into_inner().unwrap();
let stderr_bytes = Arc::try_unwrap(err_buf).unwrap().into_inner().unwrap();
let stdout_str = String::from_utf8_lossy(&stdout_bytes).into_owned();
let stderr_str = String::from_utf8_lossy(&stderr_bytes).into_owned();
Ok((s, stdout_str, stderr_str))
} else {
let _ = child.kill();
let _ = out_thread.join();
let _ = err_thread.join();
Err(format!("Timeout after {:?}", timeout))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
use std::io::Read;
#[test]
fn test_fd_redirect_guard_restores_on_drop() {
let temp_file = tempfile::NamedTempFile::new().unwrap();
let file = File::create(temp_file.path()).unwrap();
let new_fd = get_file_fd(&file);
assert!(new_fd >= 0);
{
let guard = FdRedirectGuard::redirect_stdout_to(new_fd).unwrap();
assert!(guard.is_active());
#[cfg(unix)]
{
use std::os::unix::io::FromRawFd;
use std::io::Write;
let mut f = std::mem::ManuallyDrop::new(unsafe { File::from_raw_fd(1) });
f.write_all(b"Hello via redirected stdout!").unwrap();
f.flush().unwrap();
}
#[cfg(windows)]
{
use std::os::windows::io::FromRawHandle;
use std::io::Write;
unsafe extern "C" {
fn _get_osfhandle(fd: std::os::raw::c_int) -> isize;
}
let handle = unsafe { _get_osfhandle(1) };
let mut f = std::mem::ManuallyDrop::new(unsafe { File::from_raw_handle(handle as _) });
f.write_all(b"Hello via redirected stdout!").unwrap();
f.flush().unwrap();
}
drop(guard);
}
println!("This goes to console normally.");
let mut content = String::new();
let mut read_f = File::open(temp_file.path()).unwrap();
read_f.read_to_string(&mut content).unwrap();
assert!(content.contains("Hello via redirected stdout!"));
}
#[test]
fn test_fd_redirect_guard_restores_on_panic() {
let temp_file = tempfile::NamedTempFile::new().unwrap();
let file = File::create(temp_file.path()).unwrap();
let new_fd = get_file_fd(&file);
let _ = std::panic::catch_unwind(move || {
let _guard = FdRedirectGuard::redirect_stdout_to(new_fd).unwrap();
panic!("Induced test panic while stdout redirected");
});
print!("Console restored after catch_unwind!");
use std::io::Write;
std::io::stdout().flush().unwrap();
}
}