2023-07-28 06:53:28 -05:00
|
|
|
#![cfg(any(target_family = "unix", target_family = "windows"))]
|
2023-06-07 14:51:57 -05:00
|
|
|
|
2017-03-14 00:27:12 -05:00
|
|
|
use std::fs::File;
|
|
|
|
use std::io::{Read, Write};
|
2023-06-07 11:40:25 -05:00
|
|
|
|
|
|
|
mod common;
|
2017-03-14 00:27:12 -05:00
|
|
|
|
|
|
|
#[cfg(unix)]
|
|
|
|
fn switch_stdout_to(file: File) {
|
|
|
|
use std::os::unix::prelude::*;
|
|
|
|
|
2020-09-01 16:12:52 -05:00
|
|
|
extern "C" {
|
2017-03-14 00:27:12 -05:00
|
|
|
fn dup2(old: i32, new: i32) -> i32;
|
|
|
|
}
|
|
|
|
|
|
|
|
unsafe {
|
|
|
|
assert_eq!(dup2(file.as_raw_fd(), 1), 1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(windows)]
|
|
|
|
fn switch_stdout_to(file: File) {
|
|
|
|
use std::os::windows::prelude::*;
|
|
|
|
|
|
|
|
extern "system" {
|
|
|
|
fn SetStdHandle(nStdHandle: u32, handle: *mut u8) -> i32;
|
|
|
|
}
|
|
|
|
|
|
|
|
const STD_OUTPUT_HANDLE: u32 = (-11i32) as u32;
|
|
|
|
|
|
|
|
unsafe {
|
2020-09-01 16:12:52 -05:00
|
|
|
let rc = SetStdHandle(STD_OUTPUT_HANDLE, file.into_raw_handle() as *mut _);
|
2017-03-14 00:27:12 -05:00
|
|
|
assert!(rc != 0);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-06-07 11:40:25 -05:00
|
|
|
#[test]
|
|
|
|
fn switch_stdout() {
|
|
|
|
let temp = common::tmpdir();
|
|
|
|
let path = temp.join("switch-stdout-output");
|
2017-03-14 00:27:12 -05:00
|
|
|
let f = File::create(&path).unwrap();
|
|
|
|
|
2023-06-07 11:40:25 -05:00
|
|
|
let mut stdout = std::io::stdout();
|
|
|
|
stdout.write(b"foo\n").unwrap();
|
|
|
|
stdout.flush().unwrap();
|
2017-03-14 00:27:12 -05:00
|
|
|
switch_stdout_to(f);
|
2023-06-07 11:40:25 -05:00
|
|
|
stdout.write(b"bar\n").unwrap();
|
|
|
|
stdout.flush().unwrap();
|
2017-03-14 00:27:12 -05:00
|
|
|
|
|
|
|
let mut contents = String::new();
|
|
|
|
File::open(&path).unwrap().read_to_string(&mut contents).unwrap();
|
|
|
|
assert_eq!(contents, "bar\n");
|
|
|
|
}
|