]>
Commit | Line | Data |
---|---|---|
416331ca XL |
1 | // run-pass |
2 | ||
2c00a5a8 | 3 | use std::env; |
cc61c64b XL |
4 | use std::fs::File; |
5 | use std::io::{Read, Write}; | |
2c00a5a8 | 6 | use std::path::PathBuf; |
cc61c64b XL |
7 | |
8 | #[cfg(unix)] | |
9 | fn switch_stdout_to(file: File) { | |
10 | use std::os::unix::prelude::*; | |
11 | ||
5869c6ff | 12 | extern "C" { |
cc61c64b XL |
13 | fn dup2(old: i32, new: i32) -> i32; |
14 | } | |
15 | ||
16 | unsafe { | |
17 | assert_eq!(dup2(file.as_raw_fd(), 1), 1); | |
18 | } | |
19 | } | |
20 | ||
21 | #[cfg(windows)] | |
22 | fn switch_stdout_to(file: File) { | |
23 | use std::os::windows::prelude::*; | |
24 | ||
25 | extern "system" { | |
26 | fn SetStdHandle(nStdHandle: u32, handle: *mut u8) -> i32; | |
27 | } | |
28 | ||
29 | const STD_OUTPUT_HANDLE: u32 = (-11i32) as u32; | |
30 | ||
31 | unsafe { | |
5869c6ff | 32 | let rc = SetStdHandle(STD_OUTPUT_HANDLE, file.into_raw_handle() as *mut _); |
cc61c64b XL |
33 | assert!(rc != 0); |
34 | } | |
35 | } | |
36 | ||
37 | fn main() { | |
2c00a5a8 XL |
38 | let path = PathBuf::from(env::var_os("RUST_TEST_TMPDIR").unwrap()); |
39 | let path = path.join("switch-stdout-output"); | |
cc61c64b XL |
40 | let f = File::create(&path).unwrap(); |
41 | ||
42 | println!("foo"); | |
43 | std::io::stdout().flush().unwrap(); | |
44 | switch_stdout_to(f); | |
45 | println!("bar"); | |
46 | std::io::stdout().flush().unwrap(); | |
47 | ||
48 | let mut contents = String::new(); | |
49 | File::open(&path).unwrap().read_to_string(&mut contents).unwrap(); | |
50 | assert_eq!(contents, "bar\n"); | |
51 | } |