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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#![deny(missing_docs)]
extern crate mio;
extern crate mio_extras;
#[cfg(target_os = "windows")]
extern crate winapi;
use mio::{Evented, Poll, PollOpt, Ready, Token};
use mio_extras::channel::{channel, Receiver, Sender};
use std::io::{Error, ErrorKind, Read, Result, Write};
use std::process::{Child, Command, ExitStatus};
use std::thread::spawn;
#[cfg(test)]
mod test;
pub trait CommandAsync {
fn spawn_async(&mut self) -> Result<Process>;
}
impl CommandAsync for Command {
fn spawn_async(&mut self) -> Result<Process> {
let child = self.spawn()?;
Ok(Process::from_child(child))
}
}
pub struct Process {
receiver: Receiver<ProcessEvent>,
stdin: Option<std::process::ChildStdin>,
id: u32,
}
impl Process {
pub fn try_recv(&mut self) -> std::result::Result<ProcessEvent, std::sync::mpsc::TryRecvError> {
self.receiver.try_recv()
}
pub(crate) fn from_child(mut child: Child) -> Process {
let (sender, receiver) = channel();
if let Some(stdout) = child.stdout.take() {
spawn(create_reader(stdout, sender.clone(), StdioChannel::Stdout));
}
if let Some(stderr) = child.stderr.take() {
spawn(create_reader(stderr, sender.clone(), StdioChannel::Stderr));
}
let stdin = child.stdin.take();
let id = child.id();
spawn(move || {
let result = match child.wait_with_output() {
Err(e) => {
let _ = sender.send(ProcessEvent::CommandError(e));
return;
}
Ok(r) => r,
};
if !result.stdout.is_empty() {
if SendResult::Abort
== try_send_buffer(&result.stdout, StdioChannel::Stdout, &sender)
{
return;
}
}
if !result.stderr.is_empty() {
if SendResult::Abort
== try_send_buffer(&result.stderr, StdioChannel::Stderr, &sender)
{
return;
}
}
let _ = sender.send(ProcessEvent::Exit(result.status));
});
Process {
receiver,
stdin,
id,
}
}
#[cfg(target_os = "windows")]
pub fn kill(&mut self) -> Result<()> {
use std::collections::HashMap;
use std::io::Error;
use std::mem;
use winapi::um::handleapi::{CloseHandle, INVALID_HANDLE_VALUE};
use winapi::um::processthreadsapi::{OpenProcess, TerminateProcess};
use winapi::um::tlhelp32::{
CreateToolhelp32Snapshot, Process32First, Process32Next, PROCESSENTRY32,
TH32CS_SNAPPROCESS,
};
use winapi::um::winnt::PROCESS_TERMINATE;
type ParentID = u32;
type ChildID = u32;
let mut processes = HashMap::<ParentID, Vec<ChildID>>::new();
let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
if snapshot == INVALID_HANDLE_VALUE {
unsafe {
CloseHandle(snapshot);
}
return Err(Error::last_os_error());
}
let mut process_entry_32: PROCESSENTRY32 = unsafe { mem::zeroed() };
process_entry_32.dwSize = mem::size_of::<PROCESSENTRY32>() as u32;
if 0 == unsafe { Process32First(snapshot, &mut process_entry_32) } {
unsafe {
CloseHandle(snapshot);
}
return Err(Error::last_os_error());
}
processes
.entry(process_entry_32.th32ParentProcessID)
.or_insert_with(Vec::new)
.push(process_entry_32.th32ProcessID);
while unsafe { Process32Next(snapshot, &mut process_entry_32) } != 0 {
processes
.entry(process_entry_32.th32ParentProcessID)
.or_insert_with(Vec::new)
.push(process_entry_32.th32ProcessID);
}
unsafe {
CloseHandle(snapshot);
}
fn kill_pid(pid: u32, processes: &HashMap<ParentID, Vec<ChildID>>) -> Result<()> {
if let Some(children) = processes.get(&pid) {
for child in children {
kill_pid(*child, processes)?;
}
}
let handle = unsafe { OpenProcess(PROCESS_TERMINATE, 0, pid) };
if handle.is_null() {
Err(Error::last_os_error())
} else if 0 == unsafe { TerminateProcess(handle, 0) } {
Err(Error::last_os_error())
} else {
Ok(())
}
}
kill_pid(self.id(), &processes)
}
#[cfg(target_os = "linux")]
pub fn kill(&mut self) -> Result<()> {
extern crate libc;
use std::io::Error;
let result = unsafe { libc::kill(self.id() as i32, libc::SIGKILL) };
if result == 0 {
Ok(())
} else {
Err(Error::last_os_error())
}
}
pub fn id(&self) -> u32 {
self.id
}
}
impl Write for Process {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
match self.stdin.as_mut() {
Some(ref mut stdin) => stdin.write(buf),
None => Err(Error::from(ErrorKind::NotConnected)),
}
}
fn flush(&mut self) -> Result<()> {
match self.stdin.as_mut() {
Some(ref mut stdin) => stdin.flush(),
None => Err(Error::from(ErrorKind::NotConnected)),
}
}
}
impl Evented for Process {
fn register(&self, poll: &Poll, token: Token, interest: Ready, ops: PollOpt) -> Result<()> {
self.receiver.register(poll, token, interest, ops)
}
fn reregister(&self, poll: &Poll, token: Token, interest: Ready, ops: PollOpt) -> Result<()> {
self.receiver.reregister(poll, token, interest, ops)
}
fn deregister(&self, poll: &Poll) -> Result<()> {
self.receiver.deregister(poll)
}
}
#[derive(PartialEq, Eq, Debug)]
enum SendResult {
Abort,
Ok,
}
fn try_send_buffer(
buffer: &[u8],
channel: StdioChannel,
sender: &Sender<ProcessEvent>,
) -> SendResult {
let str = match std::str::from_utf8(buffer) {
Ok(s) => s,
Err(e) => {
let _ = sender.send(ProcessEvent::Utf8Error(channel, e));
return SendResult::Abort;
}
};
if str.is_empty() {
println!("Aborting try_send_buffer because we're sending empty strings");
println!("Channel: {:?}", channel);
return SendResult::Abort;
}
if let Err(_) = sender.send(ProcessEvent::Data(channel, String::from(str))) {
SendResult::Abort
} else {
SendResult::Ok
}
}
fn create_reader<T: Read + 'static>(
mut stream: T,
sender: Sender<ProcessEvent>,
channel: StdioChannel,
) -> impl FnOnce() {
move || {
let mut buffer = [0u8; 1024];
loop {
match stream.read(&mut buffer[..]) {
Ok(0) => {
break;
}
Ok(n) => {
if SendResult::Abort == try_send_buffer(&buffer[..n], channel, &sender) {
break;
}
}
Err(e) => {
let _ = sender.send(ProcessEvent::IoError(channel, e));
break;
}
}
}
}
}
#[derive(Debug)]
pub enum ProcessEvent {
Data(StdioChannel, String),
CommandError(std::io::Error),
IoError(StdioChannel, std::io::Error),
Utf8Error(StdioChannel, std::str::Utf8Error),
Exit(ExitStatus),
}
#[derive(Copy, Clone, Debug)]
pub enum StdioChannel {
Stdout,
Stderr,
}