1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#[cfg(not(windows))]
#[macro_use]
extern crate lazy_static;
#[cfg(not(windows))]
extern crate libc;
#[cfg(not(windows))]
#[path = "unix.rs"]
mod sys;
#[cfg(windows)]
#[path = "windows.rs"]
mod sys;
use std::fs::File;
pub use sys::pipe;
pub use sys::stdio_from_file;
pub use sys::dup_stdin;
pub use sys::dup_stdout;
pub use sys::dup_stderr;
pub struct Pair {
pub read: File,
pub write: File,
}
#[cfg(test)]
mod tests {
use std::io::prelude::*;
use std::path::Path;
use std::process;
use std::thread;
use ::Pair;
#[test]
fn test_pipe_some_data() {
let mut pair = ::pipe().unwrap();
pair.write.write_all(b"some stuff").unwrap();
drop(pair.write);
let mut out = String::new();
pair.read.read_to_string(&mut out).unwrap();
assert_eq!(out, "some stuff");
}
#[test]
fn test_pipe_no_data() {
let mut pair = ::pipe().unwrap();
drop(pair.write);
let mut out = String::new();
pair.read.read_to_string(&mut out).unwrap();
assert_eq!(out, "");
}
#[test]
fn test_pipe_a_megabyte_of_data_from_another_thread() {
let data = vec![0xff; 1_000_000];
let data_copy = data.clone();
let Pair { mut read, mut write } = ::pipe().unwrap();
let joiner = thread::spawn(move || {
write.write_all(&data_copy).unwrap();
});
let mut out = Vec::new();
read.read_to_end(&mut out).unwrap();
joiner.join().unwrap();
assert_eq!(out, data);
}
#[test]
fn test_pipes_are_not_inheritable() {
let mut input_pipe = ::pipe().unwrap();
let mut output_pipe = ::pipe().unwrap();
let child_stdin = ::stdio_from_file(input_pipe.read);
let child_stdout = ::stdio_from_file(output_pipe.write);
let cat_dir = Path::new(".").join("test").join("cat");
let mut child = process::Command::new("cargo")
.arg("run")
.arg("-q")
.current_dir(&cat_dir)
.stdin(child_stdin)
.stdout(child_stdout)
.spawn()
.unwrap();
input_pipe.write.write_all(b"hello").unwrap();
drop(input_pipe.write);
let mut output = Vec::new();
output_pipe.read.read_to_end(&mut output).unwrap();
child.wait().unwrap();
assert_eq!(b"hello", &*output);
}
#[test]
fn test_duped_handles() {
let mut input_pipe = ::pipe().unwrap();
let child_stdin = ::stdio_from_file(input_pipe.read);
input_pipe.write.write_all(b"quack").unwrap();
drop(input_pipe.write);
let tee_dir = Path::new(".").join("test").join("tee");
let output = process::Command::new("cargo")
.arg("run")
.arg("-q")
.current_dir(&tee_dir)
.stdin(child_stdin)
.output()
.unwrap();
assert!(output.status.success(),
"child process returned {:#?}",
output);
assert_eq!(b"quack", &*output.stdout);
assert_eq!(b"quack", &*output.stderr);
}
}