Debian Codegraph @

third_party/rust/tokio/src/process/mod.rs

raw
1 //! An implementation of asynchronous process management for Tokio.
2 //!
3 //! This module provides a [`Command`] struct that imitates the interface of the
4 //! [`std::process::Command`] type in the standard library, but provides asynchronous versions of
5 //! functions that create processes. These functions (`spawn`, `status`, `output` and their
6 //! variants) return "future aware" types that interoperate with Tokio. The asynchronous process
7 //! support is provided through signal handling on Unix and system APIs on Windows.
8 //!
9 //! [`std::process::Command`]: std::process::Command
10 //!
11 //! # Examples
12 //!
13 //! Here's an example program which will spawn `echo hello world` and then wait
14 //! for it complete.
15 //!
16 //! ```no_run
17 //! use tokio::process::Command;
18 //!
19 //! #[tokio::main]
20 //! async fn main() -> Result<(), Box<dyn std::error::Error>> {
21 //! // The usage is similar as with the standard library's `Command` type
22 //! let mut child = Command::new("echo")
23 //! .arg("hello")
24 //! .arg("world")
25 //! .spawn()
26 //! .expect("failed to spawn");
27 //!
28 //! // Await until the command completes
29 //! let status = child.wait().await?;
30 //! println!("the command exited with: {}", status);
31 //! Ok(())
32 //! }
33 //! ```
34 //!
35 //! Next, let's take a look at an example where we not only spawn `echo hello
36 //! world` but we also capture its output.
37 //!
38 //! ```no_run
39 //! use tokio::process::Command;
40 //!
41 //! #[tokio::main]
42 //! async fn main() -> Result<(), Box<dyn std::error::Error>> {
43 //! // Like above, but use `output` which returns a future instead of
44 //! // immediately returning the `Child`.
45 //! let output = Command::new("echo").arg("hello").arg("world")
46 //! .output();
47 //!
48 //! let output = output.await?;
49 //!
50 //! assert!(output.status.success());
51 //! assert_eq!(output.stdout, b"hello world\n");
52 //! Ok(())
53 //! }
54 //! ```
55 //!
56 //! We can also read input line by line.
57 //!
58 //! ```no_run
59 //! use tokio::io::{BufReader, AsyncBufReadExt};
60 //! use tokio::process::Command;
61 //!
62 //! use std::process::Stdio;
63 //!
64 //! #[tokio::main]
65 //! async fn main() -> Result<(), Box<dyn std::error::Error>> {
66 //! let mut cmd = Command::new("cat");
67 //!
68 //! // Specify that we want the command's standard output piped back to us.
69 //! // By default, standard input/output/error will be inherited from the
70 //! // current process (for example, this means that standard input will
71 //! // come from the keyboard and standard output/error will go directly to
72 //! // the terminal if this process is invoked from the command line).
73 //! cmd.stdout(Stdio::piped());
74 //!
75 //! let mut child = cmd.spawn()
76 //! .expect("failed to spawn command");
77 //!
78 //! let stdout = child.stdout.take()
79 //! .expect("child did not have a handle to stdout");
80 //!
81 //! let mut reader = BufReader::new(stdout).lines();
82 //!
83 //! // Ensure the child process is spawned in the runtime so it can
84 //! // make progress on its own while we await for any output.
85 //! tokio::spawn(async move {
86 //! let status = child.wait().await
87 //! .expect("child process encountered an error");
88 //!
89 //! println!("child status was: {}", status);
90 //! });
91 //!
92 //! while let Some(line) = reader.next_line().await? {
93 //! println!("Line: {}", line);
94 //! }
95 //!
96 //! Ok(())
97 //! }
98 //! ```
99 //!
100 //! Here is another example using `sort` writing into the child process
101 //! standard input, capturing the output of the sorted text.
102 //!
103 //! ```no_run
104 //! use tokio::io::AsyncWriteExt;
105 //! use tokio::process::Command;
106 //!
107 //! use std::process::Stdio;
108 //!
109 //! #[tokio::main]
110 //! async fn main() -> Result<(), Box<dyn std::error::Error>> {
111 //! let mut cmd = Command::new("sort");
112 //!
113 //! // Specifying that we want pipe both the output and the input.
114 //! // Similarly to capturing the output, by configuring the pipe
115 //! // to stdin it can now be used as an asynchronous writer.
116 //! cmd.stdout(Stdio::piped());
117 //! cmd.stdin(Stdio::piped());
118 //!
119 //! let mut child = cmd.spawn().expect("failed to spawn command");
120 //!
121 //! // These are the animals we want to sort
122 //! let animals: &[&str] = &["dog", "bird", "frog", "cat", "fish"];
123 //!
124 //! let mut stdin = child
125 //! .stdin
126 //! .take()
127 //! .expect("child did not have a handle to stdin");
128 //!
129 //! // Write our animals to the child process
130 //! // Note that the behavior of `sort` is to buffer _all input_ before writing any output.
131 //! // In the general sense, it is recommended to write to the child in a separate task as
132 //! // awaiting its exit (or output) to avoid deadlocks (for example, the child tries to write
133 //! // some output but gets stuck waiting on the parent to read from it, meanwhile the parent
134 //! // is stuck waiting to write its input completely before reading the output).
135 //! stdin
136 //! .write(animals.join("\n").as_bytes())
137 //! .await
138 //! .expect("could not write to stdin");
139 //!
140 //! // We drop the handle here which signals EOF to the child process.
141 //! // This tells the child process that it there is no more data on the pipe.
142 //! drop(stdin);
143 //!
144 //! let op = child.wait_with_output().await?;
145 //!
146 //! // Results should come back in sorted order
147 //! assert_eq!(op.stdout, "bird\ncat\ndog\nfish\nfrog\n".as_bytes());
148 //!
149 //! Ok(())
150 //! }
151 //! ```
152 //!
153 //! With some coordination, we can also pipe the output of one command into
154 //! another.
155 //!
156 //! ```no_run
157 //! use tokio::join;
158 //! use tokio::process::Command;
159 //! use std::process::Stdio;
160 //!
161 //! #[tokio::main]
162 //! async fn main() -> Result<(), Box<dyn std::error::Error>> {
163 //! let mut echo = Command::new("echo")
164 //! .arg("hello world!")
165 //! .stdout(Stdio::piped())
166 //! .spawn()
167 //! .expect("failed to spawn echo");
168 //!
169 //! let tr_stdin: Stdio = echo
170 //! .stdout
171 //! .take()
172 //! .unwrap()
173 //! .try_into()
174 //! .expect("failed to convert to Stdio");
175 //!
176 //! let tr = Command::new("tr")
177 //! .arg("a-z")
178 //! .arg("A-Z")
179 //! .stdin(tr_stdin)
180 //! .stdout(Stdio::piped())
181 //! .spawn()
182 //! .expect("failed to spawn tr");
183 //!
184 //! let (echo_result, tr_output) = join!(echo.wait(), tr.wait_with_output());
185 //!
186 //! assert!(echo_result.unwrap().success());
187 //!
188 //! let tr_output = tr_output.expect("failed to await tr");
189 //! assert!(tr_output.status.success());
190 //!
191 //! assert_eq!(tr_output.stdout, b"HELLO WORLD!\n");
192 //!
193 //! Ok(())
194 //! }
195 //! ```
196 //!
197 //! # Caveats
198 //!
199 //! ## Dropping/Cancellation
200 //!
201 //! Similar to the behavior to the standard library, and unlike the futures
202 //! paradigm of dropping-implies-cancellation, a spawned process will, by
203 //! default, continue to execute even after the `Child` handle has been dropped.
204 //!
205 //! The [`Command::kill_on_drop`] method can be used to modify this behavior
206 //! and kill the child process if the `Child` wrapper is dropped before it
207 //! has exited.
208 //!
209 //! ## Unix Processes
210 //!
211 //! On Unix platforms processes must be "reaped" by their parent process after
212 //! they have exited in order to release all OS resources. A child process which
213 //! has exited, but has not yet been reaped by its parent is considered a "zombie"
214 //! process. Such processes continue to count against limits imposed by the system,
215 //! and having too many zombie processes present can prevent additional processes
216 //! from being spawned.
217 //!
218 //! The tokio runtime will, on a best-effort basis, attempt to reap and clean up
219 //! any process which it has spawned. No additional guarantees are made with regard to
220 //! how quickly or how often this procedure will take place.
221 //!
222 //! It is recommended to avoid dropping a [`Child`] process handle before it has been
223 //! fully `await`ed if stricter cleanup guarantees are required.
224 //!
225 //! [`Command`]: crate::process::Command
226 //! [`Command::kill_on_drop`]: crate::process::Command::kill_on_drop
227 //! [`Child`]: crate::process::Child
228
229 #[path = "unix/mod.rs"]
230 #[cfg(unix)]
231 mod imp;
232
233 #[cfg(unix)]
234 pub(crate) mod unix {
235 pub(crate) use super::imp::*;
236 }
237
238 #[path = "windows.rs"]
239 #[cfg(windows)]
240 mod imp;
241
242 mod kill;
243
244 use crate::io::{AsyncRead, AsyncWrite, ReadBuf};
245 use crate::process::kill::Kill;
246
247 use std::ffi::OsStr;
248 use std::future::Future;
249 use std::io;
250 use std::path::Path;
251 use std::pin::Pin;
252 use std::process::{Command as StdCommand, ExitStatus, Output, Stdio};
253 use std::task::Context;
254 use std::task::Poll;
255
256 #[cfg(unix)]
257 use std::os::unix::process::CommandExt;
258 #[cfg(windows)]
259 use std::os::windows::process::CommandExt;
260
261 cfg_windows! {
262 use crate::os::windows::io::{AsRawHandle, RawHandle};
263 }
264
265 /// This structure mimics the API of [`std::process::Command`] found in the standard library, but
266 /// replaces functions that create a process with an asynchronous variant. The main provided
267 /// asynchronous functions are [spawn](Command::spawn), [status](Command::status), and
268 /// [output](Command::output).
269 ///
270 /// `Command` uses asynchronous versions of some `std` types (for example [`Child`]).
271 ///
272 /// [`std::process::Command`]: std::process::Command
273 /// [`Child`]: struct@Child
274 #[derive(Debug)]
275 pub struct Command {
276 std: StdCommand,
277 kill_on_drop: bool,
278 }
279
280 pub(crate) struct SpawnedChild {
281 child: imp::Child,
282 stdin: Option<imp::ChildStdio>,
283 stdout: Option<imp::ChildStdio>,
284 stderr: Option<imp::ChildStdio>,
285 }
286
287 impl Command {
288 /// Constructs a new `Command` for launching the program at
289 /// path `program`, with the following default configuration:
290 ///
291 /// * No arguments to the program
292 /// * Inherit the current process's environment
293 /// * Inherit the current process's working directory
294 /// * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output`
295 ///
296 /// Builder methods are provided to change these defaults and
297 /// otherwise configure the process.
298 ///
299 /// If `program` is not an absolute path, the `PATH` will be searched in
300 /// an OS-defined way.
301 ///
302 /// The search path to be used may be controlled by setting the
303 /// `PATH` environment variable on the Command,
304 /// but this has some implementation limitations on Windows
305 /// (see issue [rust-lang/rust#37519]).
306 ///
307 /// # Examples
308 ///
309 /// Basic usage:
310 ///
311 /// ```no_run
312 /// use tokio::process::Command;
313 /// let mut command = Command::new("sh");
314 /// # let _ = command.output(); // assert borrow checker
315 /// ```
316 ///
317 /// [rust-lang/rust#37519]: https://github.com/rust-lang/rust/issues/37519
318 pub fn new<S: AsRef<OsStr>>(program: S) -> Command {
319 Self::from(StdCommand::new(program))
320 }
321
322 /// Cheaply convert to a `&std::process::Command` for places where the type from the standard
323 /// library is expected.
324 pub fn as_std(&self) -> &StdCommand {
325 &self.std
326 }
327
328 /// Cheaply convert to a `&mut std::process::Command` for places where the type from the
329 /// standard library is expected.
330 pub fn as_std_mut(&mut self) -> &mut StdCommand {
331 &mut self.std
332 }
333
334 /// Adds an argument to pass to the program.
335 ///
336 /// Only one argument can be passed per use. So instead of:
337 ///
338 /// ```no_run
339 /// let mut command = tokio::process::Command::new("sh");
340 /// command.arg("-C /path/to/repo");
341 ///
342 /// # let _ = command.output(); // assert borrow checker
343 /// ```
344 ///
345 /// usage would be:
346 ///
347 /// ```no_run
348 /// let mut command = tokio::process::Command::new("sh");
349 /// command.arg("-C");
350 /// command.arg("/path/to/repo");
351 ///
352 /// # let _ = command.output(); // assert borrow checker
353 /// ```
354 ///
355 /// To pass multiple arguments see [`args`].
356 ///
357 /// [`args`]: method@Self::args
358 ///
359 /// # Examples
360 ///
361 /// Basic usage:
362 ///
363 /// ```no_run
364 /// # async fn test() { // allow using await
365 /// use tokio::process::Command;
366 ///
367 /// let output = Command::new("ls")
368 /// .arg("-l")
369 /// .arg("-a")
370 /// .output().await.unwrap();
371 /// # }
372 ///
373 /// ```
374 pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command {
375 self.std.arg(arg);
376 self
377 }
378
379 /// Adds multiple arguments to pass to the program.
380 ///
381 /// To pass a single argument see [`arg`].
382 ///
383 /// [`arg`]: method@Self::arg
384 ///
385 /// # Examples
386 ///
387 /// Basic usage:
388 ///
389 /// ```no_run
390 /// # async fn test() { // allow using await
391 /// use tokio::process::Command;
392 ///
393 /// let output = Command::new("ls")
394 /// .args(&["-l", "-a"])
395 /// .output().await.unwrap();
396 /// # }
397 /// ```
398 pub fn args<I, S>(&mut self, args: I) -> &mut Command
399 where
400 I: IntoIterator<Item = S>,
401 S: AsRef<OsStr>,
402 {
403 self.std.args(args);
404 self
405 }
406
407 cfg_windows! {
408 /// Append literal text to the command line without any quoting or escaping.
409 ///
410 /// This is useful for passing arguments to `cmd.exe /c`, which doesn't follow
411 /// `CommandLineToArgvW` escaping rules.
412 pub fn raw_arg<S: AsRef<OsStr>>(&mut self, text_to_append_as_is: S) -> &mut Command {
413 self.std.raw_arg(text_to_append_as_is);
414 self
415 }
416 }
417
418 /// Inserts or updates an environment variable mapping.
419 ///
420 /// Note that environment variable names are case-insensitive (but case-preserving) on Windows,
421 /// and case-sensitive on all other platforms.
422 ///
423 /// # Examples
424 ///
425 /// Basic usage:
426 ///
427 /// ```no_run
428 /// # async fn test() { // allow using await
429 /// use tokio::process::Command;
430 ///
431 /// let output = Command::new("ls")
432 /// .env("PATH", "/bin")
433 /// .output().await.unwrap();
434 /// # }
435 /// ```
436 pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command
437 where
438 K: AsRef<OsStr>,
439 V: AsRef<OsStr>,
440 {
441 self.std.env(key, val);
442 self
443 }
444
445 /// Adds or updates multiple environment variable mappings.
446 ///
447 /// # Examples
448 ///
449 /// Basic usage:
450 ///
451 /// ```no_run
452 /// # async fn test() { // allow using await
453 /// use tokio::process::Command;
454 /// use std::process::{Stdio};
455 /// use std::env;
456 /// use std::collections::HashMap;
457 ///
458 /// let filtered_env : HashMap<String, String> =
459 /// env::vars().filter(|&(ref k, _)|
460 /// k == "TERM" || k == "TZ" || k == "LANG" || k == "PATH"
461 /// ).collect();
462 ///
463 /// let output = Command::new("printenv")
464 /// .stdin(Stdio::null())
465 /// .stdout(Stdio::inherit())
466 /// .env_clear()
467 /// .envs(&filtered_env)
468 /// .output().await.unwrap();
469 /// # }
470 /// ```
471 pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Command
472 where
473 I: IntoIterator<Item = (K, V)>,
474 K: AsRef<OsStr>,
475 V: AsRef<OsStr>,
476 {
477 self.std.envs(vars);
478 self
479 }
480
481 /// Removes an environment variable mapping.
482 ///
483 /// # Examples
484 ///
485 /// Basic usage:
486 ///
487 /// ```no_run
488 /// # async fn test() { // allow using await
489 /// use tokio::process::Command;
490 ///
491 /// let output = Command::new("ls")
492 /// .env_remove("PATH")
493 /// .output().await.unwrap();
494 /// # }
495 /// ```
496 pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Command {
497 self.std.env_remove(key);
498 self
499 }
500
501 /// Clears the entire environment map for the child process.
502 ///
503 /// # Examples
504 ///
505 /// Basic usage:
506 ///
507 /// ```no_run
508 /// # async fn test() { // allow using await
509 /// use tokio::process::Command;
510 ///
511 /// let output = Command::new("ls")
512 /// .env_clear()
513 /// .output().await.unwrap();
514 /// # }
515 /// ```
516 pub fn env_clear(&mut self) -> &mut Command {
517 self.std.env_clear();
518 self
519 }
520
521 /// Sets the working directory for the child process.
522 ///
523 /// # Platform-specific behavior
524 ///
525 /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous
526 /// whether it should be interpreted relative to the parent's working
527 /// directory or relative to `current_dir`. The behavior in this case is
528 /// platform specific and unstable, and it's recommended to use
529 /// [`canonicalize`] to get an absolute program path instead.
530 ///
531 /// [`canonicalize`]: crate::fs::canonicalize()
532 ///
533 /// # Examples
534 ///
535 /// Basic usage:
536 ///
537 /// ```no_run
538 /// # async fn test() { // allow using await
539 /// use tokio::process::Command;
540 ///
541 /// let output = Command::new("ls")
542 /// .current_dir("/bin")
543 /// .output().await.unwrap();
544 /// # }
545 /// ```
546 pub fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Command {
547 self.std.current_dir(dir);
548 self
549 }
550
551 /// Sets configuration for the child process's standard input (stdin) handle.
552 ///
553 /// Defaults to [`inherit`].
554 ///
555 /// [`inherit`]: std::process::Stdio::inherit
556 ///
557 /// # Examples
558 ///
559 /// Basic usage:
560 ///
561 /// ```no_run
562 /// # async fn test() { // allow using await
563 /// use std::process::{Stdio};
564 /// use tokio::process::Command;
565 ///
566 /// let output = Command::new("ls")
567 /// .stdin(Stdio::null())
568 /// .output().await.unwrap();
569 /// # }
570 /// ```
571 pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
572 self.std.stdin(cfg);
573 self
574 }
575
576 /// Sets configuration for the child process's standard output (stdout) handle.
577 ///
578 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
579 /// defaults to [`piped`] when used with `output`.
580 ///
581 /// [`inherit`]: std::process::Stdio::inherit
582 /// [`piped`]: std::process::Stdio::piped
583 ///
584 /// # Examples
585 ///
586 /// Basic usage:
587 ///
588 /// ```no_run
589 /// # async fn test() { // allow using await
590 /// use tokio::process::Command;
591 /// use std::process::Stdio;
592 ///
593 /// let output = Command::new("ls")
594 /// .stdout(Stdio::null())
595 /// .output().await.unwrap();
596 /// # }
597 /// ```
598 pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
599 self.std.stdout(cfg);
600 self
601 }
602
603 /// Sets configuration for the child process's standard error (stderr) handle.
604 ///
605 /// Defaults to [`inherit`] when used with `spawn` or `status`, and
606 /// defaults to [`piped`] when used with `output`.
607 ///
608 /// [`inherit`]: std::process::Stdio::inherit
609 /// [`piped`]: std::process::Stdio::piped
610 ///
611 /// # Examples
612 ///
613 /// Basic usage:
614 ///
615 /// ```no_run
616 /// # async fn test() { // allow using await
617 /// use tokio::process::Command;
618 /// use std::process::{Stdio};
619 ///
620 /// let output = Command::new("ls")
621 /// .stderr(Stdio::null())
622 /// .output().await.unwrap();
623 /// # }
624 /// ```
625 pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command {
626 self.std.stderr(cfg);
627 self
628 }
629
630 /// Controls whether a `kill` operation should be invoked on a spawned child
631 /// process when its corresponding `Child` handle is dropped.
632 ///
633 /// By default, this value is assumed to be `false`, meaning the next spawned
634 /// process will not be killed on drop, similar to the behavior of the standard
635 /// library.
636 ///
637 /// # Caveats
638 ///
639 /// On Unix platforms processes must be "reaped" by their parent process after
640 /// they have exited in order to release all OS resources. A child process which
641 /// has exited, but has not yet been reaped by its parent is considered a "zombie"
642 /// process. Such processes continue to count against limits imposed by the system,
643 /// and having too many zombie processes present can prevent additional processes
644 /// from being spawned.
645 ///
646 /// Although issuing a `kill` signal to the child process is a synchronous
647 /// operation, the resulting zombie process cannot be `.await`ed inside of the
648 /// destructor to avoid blocking other tasks. The tokio runtime will, on a
649 /// best-effort basis, attempt to reap and clean up such processes in the
650 /// background, but no additional guarantees are made with regard to
651 /// how quickly or how often this procedure will take place.
652 ///
653 /// If stronger guarantees are required, it is recommended to avoid dropping
654 /// a [`Child`] handle where possible, and instead utilize `child.wait().await`
655 /// or `child.kill().await` where possible.
656 pub fn kill_on_drop(&mut self, kill_on_drop: bool) -> &mut Command {
657 self.kill_on_drop = kill_on_drop;
658 self
659 }
660
661 cfg_windows! {
662 /// Sets the [process creation flags][1] to be passed to `CreateProcess`.
663 ///
664 /// These will always be ORed with `CREATE_UNICODE_ENVIRONMENT`.
665 ///
666 /// [1]: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684863(v=vs.85).aspx
667 pub fn creation_flags(&mut self, flags: u32) -> &mut Command {
668 self.std.creation_flags(flags);
669 self
670 }
671 }
672
673 /// Sets the child process's user ID. This translates to a
674 /// `setuid` call in the child process. Failure in the `setuid`
675 /// call will cause the spawn to fail.
676 #[cfg(unix)]
677 #[cfg_attr(docsrs, doc(cfg(unix)))]
678 pub fn uid(&mut self, id: u32) -> &mut Command {
679 #[cfg(target_os = "nto")]
680 let id = id as i32;
681 self.std.uid(id);
682 self
683 }
684
685 /// Similar to `uid` but sets the group ID of the child process. This has
686 /// the same semantics as the `uid` field.
687 #[cfg(unix)]
688 #[cfg_attr(docsrs, doc(cfg(unix)))]
689 pub fn gid(&mut self, id: u32) -> &mut Command {
690 #[cfg(target_os = "nto")]
691 let id = id as i32;
692 self.std.gid(id);
693 self
694 }
695
696 /// Sets executable argument.
697 ///
698 /// Set the first process argument, `argv[0]`, to something other than the
699 /// default executable path.
700 #[cfg(unix)]
701 #[cfg_attr(docsrs, doc(cfg(unix)))]
702 pub fn arg0<S>(&mut self, arg: S) -> &mut Command
703 where
704 S: AsRef<OsStr>,
705 {
706 self.std.arg0(arg);
707 self
708 }
709
710 /// Schedules a closure to be run just before the `exec` function is
711 /// invoked.
712 ///
713 /// The closure is allowed to return an I/O error whose OS error code will
714 /// be communicated back to the parent and returned as an error from when
715 /// the spawn was requested.
716 ///
717 /// Multiple closures can be registered and they will be called in order of
718 /// their registration. If a closure returns `Err` then no further closures
719 /// will be called and the spawn operation will immediately return with a
720 /// failure.
721 ///
722 /// # Safety
723 ///
724 /// This closure will be run in the context of the child process after a
725 /// `fork`. This primarily means that any modifications made to memory on
726 /// behalf of this closure will **not** be visible to the parent process.
727 /// This is often a very constrained environment where normal operations
728 /// like `malloc` or acquiring a mutex are not guaranteed to work (due to
729 /// other threads perhaps still running when the `fork` was run).
730 ///
731 /// This also means that all resources such as file descriptors and
732 /// memory-mapped regions got duplicated. It is your responsibility to make
733 /// sure that the closure does not violate library invariants by making
734 /// invalid use of these duplicates.
735 ///
736 /// When this closure is run, aspects such as the stdio file descriptors and
737 /// working directory have successfully been changed, so output to these
738 /// locations may not appear where intended.
739 #[cfg(unix)]
740 #[cfg_attr(docsrs, doc(cfg(unix)))]
741 pub unsafe fn pre_exec<F>(&mut self, f: F) -> &mut Command
742 where
743 F: FnMut() -> io::Result<()> + Send + Sync + 'static,
744 {
745 self.std.pre_exec(f);
746 self
747 }
748
749 /// Sets the process group ID (PGID) of the child process. Equivalent to a
750 /// `setpgid` call in the child process, but may be more efficient.
751 ///
752 /// Process groups determine which processes receive signals.
753 ///
754 /// **Note**: This is an [unstable API][unstable] but will be stabilised once
755 /// tokio's `MSRV` is sufficiently new. See [the documentation on
756 /// unstable features][unstable] for details about using unstable features.
757 ///
758 /// If you want similar behavior without using this unstable feature you can
759 /// create a [`std::process::Command`] and convert that into a
760 /// [`tokio::process::Command`] using the `From` trait.
761 ///
762 /// [unstable]: crate#unstable-features
763 /// [`tokio::process::Command`]: crate::process::Command
764 ///
765 /// ```no_run
766 /// # async fn test() { // allow using await
767 /// use tokio::process::Command;
768 ///
769 /// let output = Command::new("ls")
770 /// .process_group(0)
771 /// .output().await.unwrap();
772 /// # }
773 /// ```
774 #[cfg(unix)]
775 #[cfg(tokio_unstable)]
776 #[cfg_attr(docsrs, doc(cfg(all(unix, tokio_unstable))))]
777 pub fn process_group(&mut self, pgroup: i32) -> &mut Command {
778 self.std.process_group(pgroup);
779 self
780 }
781
782 /// Executes the command as a child process, returning a handle to it.
783 ///
784 /// By default, stdin, stdout and stderr are inherited from the parent.
785 ///
786 /// This method will spawn the child process synchronously and return a
787 /// handle to a future-aware child process. The `Child` returned implements
788 /// `Future` itself to acquire the `ExitStatus` of the child, and otherwise
789 /// the `Child` has methods to acquire handles to the stdin, stdout, and
790 /// stderr streams.
791 ///
792 /// All I/O this child does will be associated with the current default
793 /// event loop.
794 ///
795 /// # Examples
796 ///
797 /// Basic usage:
798 ///
799 /// ```no_run
800 /// use tokio::process::Command;
801 ///
802 /// async fn run_ls() -> std::process::ExitStatus {
803 /// Command::new("ls")
804 /// .spawn()
805 /// .expect("ls command failed to start")
806 /// .wait()
807 /// .await
808 /// .expect("ls command failed to run")
809 /// }
810 /// ```
811 ///
812 /// # Caveats
813 ///
814 /// ## Dropping/Cancellation
815 ///
816 /// Similar to the behavior to the standard library, and unlike the futures
817 /// paradigm of dropping-implies-cancellation, a spawned process will, by
818 /// default, continue to execute even after the `Child` handle has been dropped.
819 ///
820 /// The [`Command::kill_on_drop`] method can be used to modify this behavior
821 /// and kill the child process if the `Child` wrapper is dropped before it
822 /// has exited.
823 ///
824 /// ## Unix Processes
825 ///
826 /// On Unix platforms processes must be "reaped" by their parent process after
827 /// they have exited in order to release all OS resources. A child process which
828 /// has exited, but has not yet been reaped by its parent is considered a "zombie"
829 /// process. Such processes continue to count against limits imposed by the system,
830 /// and having too many zombie processes present can prevent additional processes
831 /// from being spawned.
832 ///
833 /// The tokio runtime will, on a best-effort basis, attempt to reap and clean up
834 /// any process which it has spawned. No additional guarantees are made with regard to
835 /// how quickly or how often this procedure will take place.
836 ///
837 /// It is recommended to avoid dropping a [`Child`] process handle before it has been
838 /// fully `await`ed if stricter cleanup guarantees are required.
839 ///
840 /// [`Command`]: crate::process::Command
841 /// [`Command::kill_on_drop`]: crate::process::Command::kill_on_drop
842 /// [`Child`]: crate::process::Child
843 ///
844 /// # Errors
845 ///
846 /// On Unix platforms this method will fail with `std::io::ErrorKind::WouldBlock`
847 /// if the system process limit is reached (which includes other applications
848 /// running on the system).
849 pub fn spawn(&mut self) -> io::Result<Child> {
850 imp::spawn_child(&mut self.std).map(|spawned_child| Child {
851 child: FusedChild::Child(ChildDropGuard {
852 inner: spawned_child.child,
853 kill_on_drop: self.kill_on_drop,
854 }),
855 stdin: spawned_child.stdin.map(|inner| ChildStdin { inner }),
856 stdout: spawned_child.stdout.map(|inner| ChildStdout { inner }),
857 stderr: spawned_child.stderr.map(|inner| ChildStderr { inner }),
858 })
859 }
860
861 /// Executes the command as a child process, waiting for it to finish and
862 /// collecting its exit status.
863 ///
864 /// By default, stdin, stdout and stderr are inherited from the parent.
865 /// If any input/output handles are set to a pipe then they will be immediately
866 /// closed after the child is spawned.
867 ///
868 /// All I/O this child does will be associated with the current default
869 /// event loop.
870 ///
871 /// The destructor of the future returned by this function will kill
872 /// the child if [`kill_on_drop`] is set to true.
873 ///
874 /// [`kill_on_drop`]: fn@Self::kill_on_drop
875 ///
876 /// # Errors
877 ///
878 /// This future will return an error if the child process cannot be spawned
879 /// or if there is an error while awaiting its status.
880 ///
881 /// On Unix platforms this method will fail with `std::io::ErrorKind::WouldBlock`
882 /// if the system process limit is reached (which includes other applications
883 /// running on the system).
884 ///
885 /// # Examples
886 ///
887 /// Basic usage:
888 ///
889 /// ```no_run
890 /// use tokio::process::Command;
891 ///
892 /// async fn run_ls() -> std::process::ExitStatus {
893 /// Command::new("ls")
894 /// .status()
895 /// .await
896 /// .expect("ls command failed to run")
897 /// }
898 /// ```
899 pub fn status(&mut self) -> impl Future<Output = io::Result<ExitStatus>> {
900 let child = self.spawn();
901
902 async {
903 let mut child = child?;
904
905 // Ensure we close any stdio handles so we can't deadlock
906 // waiting on the child which may be waiting to read/write
907 // to a pipe we're holding.
908 child.stdin.take();
909 child.stdout.take();
910 child.stderr.take();
911
912 child.wait().await
913 }
914 }
915
916 /// Executes the command as a child process, waiting for it to finish and
917 /// collecting all of its output.
918 ///
919 /// > **Note**: this method, unlike the standard library, will
920 /// > unconditionally configure the stdout/stderr handles to be pipes, even
921 /// > if they have been previously configured. If this is not desired then
922 /// > the `spawn` method should be used in combination with the
923 /// > `wait_with_output` method on child.
924 ///
925 /// This method will return a future representing the collection of the
926 /// child process's stdout/stderr. It will resolve to
927 /// the `Output` type in the standard library, containing `stdout` and
928 /// `stderr` as `Vec<u8>` along with an `ExitStatus` representing how the
929 /// process exited.
930 ///
931 /// All I/O this child does will be associated with the current default
932 /// event loop.
933 ///
934 /// The destructor of the future returned by this function will kill
935 /// the child if [`kill_on_drop`] is set to true.
936 ///
937 /// [`kill_on_drop`]: fn@Self::kill_on_drop
938 ///
939 /// # Errors
940 ///
941 /// This future will return an error if the child process cannot be spawned
942 /// or if there is an error while awaiting its status.
943 ///
944 /// On Unix platforms this method will fail with `std::io::ErrorKind::WouldBlock`
945 /// if the system process limit is reached (which includes other applications
946 /// running on the system).
947 /// # Examples
948 ///
949 /// Basic usage:
950 ///
951 /// ```no_run
952 /// use tokio::process::Command;
953 ///
954 /// async fn run_ls() {
955 /// let output: std::process::Output = Command::new("ls")
956 /// .output()
957 /// .await
958 /// .expect("ls command failed to run");
959 /// println!("stderr of ls: {:?}", output.stderr);
960 /// }
961 /// ```
962 pub fn output(&mut self) -> impl Future<Output = io::Result<Output>> {
963 self.std.stdout(Stdio::piped());
964 self.std.stderr(Stdio::piped());
965
966 let child = self.spawn();
967
968 async { child?.wait_with_output().await }
969 }
970 }
971
972 impl From<StdCommand> for Command {
973 fn from(std: StdCommand) -> Command {
974 Command {
975 std,
976 kill_on_drop: false,
977 }
978 }
979 }
980
981 /// A drop guard which can ensure the child process is killed on drop if specified.
982 #[derive(Debug)]
983 struct ChildDropGuard<T: Kill> {
984 inner: T,
985 kill_on_drop: bool,
986 }
987
988 impl<T: Kill> Kill for ChildDropGuard<T> {
989 fn kill(&mut self) -> io::Result<()> {
990 let ret = self.inner.kill();
991
992 if ret.is_ok() {
993 self.kill_on_drop = false;
994 }
995
996 ret
997 }
998 }
999
1000 impl<T: Kill> Drop for ChildDropGuard<T> {
1001 fn drop(&mut self) {
1002 if self.kill_on_drop {
1003 drop(self.kill());
1004 }
1005 }
1006 }
1007
1008 impl<T, E, F> Future for ChildDropGuard<F>
1009 where
1010 F: Future<Output = Result<T, E>> + Kill + Unpin,
1011 {
1012 type Output = Result<T, E>;
1013
1014 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1015 ready!(crate::trace::trace_leaf(cx));
1016 // Keep track of task budget
1017 let coop = ready!(crate::runtime::coop::poll_proceed(cx));
1018
1019 let ret = Pin::new(&mut self.inner).poll(cx);
1020
1021 if let Poll::Ready(Ok(_)) = ret {
1022 // Avoid the overhead of trying to kill a reaped process
1023 self.kill_on_drop = false;
1024 }
1025
1026 if ret.is_ready() {
1027 coop.made_progress();
1028 }
1029
1030 ret
1031 }
1032 }
1033
1034 /// Keeps track of the exit status of a child process without worrying about
1035 /// polling the underlying futures even after they have completed.
1036 #[derive(Debug)]
1037 enum FusedChild {
1038 Child(ChildDropGuard<imp::Child>),
1039 Done(ExitStatus),
1040 }
1041
1042 /// Representation of a child process spawned onto an event loop.
1043 ///
1044 /// # Caveats
1045 /// Similar to the behavior to the standard library, and unlike the futures
1046 /// paradigm of dropping-implies-cancellation, a spawned process will, by
1047 /// default, continue to execute even after the `Child` handle has been dropped.
1048 ///
1049 /// The `Command::kill_on_drop` method can be used to modify this behavior
1050 /// and kill the child process if the `Child` wrapper is dropped before it
1051 /// has exited.
1052 #[derive(Debug)]
1053 pub struct Child {
1054 child: FusedChild,
1055
1056 /// The handle for writing to the child's standard input (stdin), if it has
1057 /// been captured. To avoid partially moving the `child` and thus blocking
1058 /// yourself from calling functions on `child` while using `stdin`, you might
1059 /// find it helpful to do:
1060 ///
1061 /// ```no_run
1062 /// # let mut child = tokio::process::Command::new("echo").spawn().unwrap();
1063 /// let stdin = child.stdin.take().unwrap();
1064 /// ```
1065 pub stdin: Option<ChildStdin>,
1066
1067 /// The handle for reading from the child's standard output (stdout), if it
1068 /// has been captured. You might find it helpful to do
1069 ///
1070 /// ```no_run
1071 /// # let mut child = tokio::process::Command::new("echo").spawn().unwrap();
1072 /// let stdout = child.stdout.take().unwrap();
1073 /// ```
1074 ///
1075 /// to avoid partially moving the `child` and thus blocking yourself from calling
1076 /// functions on `child` while using `stdout`.
1077 pub stdout: Option<ChildStdout>,
1078
1079 /// The handle for reading from the child's standard error (stderr), if it
1080 /// has been captured. You might find it helpful to do
1081 ///
1082 /// ```no_run
1083 /// # let mut child = tokio::process::Command::new("echo").spawn().unwrap();
1084 /// let stderr = child.stderr.take().unwrap();
1085 /// ```
1086 ///
1087 /// to avoid partially moving the `child` and thus blocking yourself from calling
1088 /// functions on `child` while using `stderr`.
1089 pub stderr: Option<ChildStderr>,
1090 }
1091
1092 impl Child {
1093 /// Returns the OS-assigned process identifier associated with this child
1094 /// while it is still running.
1095 ///
1096 /// Once the child has been polled to completion this will return `None`.
1097 /// This is done to avoid confusion on platforms like Unix where the OS
1098 /// identifier could be reused once the process has completed.
1099 pub fn id(&self) -> Option<u32> {
1100 match &self.child {
1101 FusedChild::Child(child) => Some(child.inner.id()),
1102 FusedChild::Done(_) => None,
1103 }
1104 }
1105
1106 cfg_windows! {
1107 /// Extracts the raw handle of the process associated with this child while
1108 /// it is still running. Returns `None` if the child has exited.
1109 pub fn raw_handle(&self) -> Option<RawHandle> {
1110 match &self.child {
1111 FusedChild::Child(c) => Some(c.inner.as_raw_handle()),
1112 FusedChild::Done(_) => None,
1113 }
1114 }
1115 }
1116
1117 /// Attempts to force the child to exit, but does not wait for the request
1118 /// to take effect.
1119 ///
1120 /// On Unix platforms, this is the equivalent to sending a `SIGKILL`. Note
1121 /// that on Unix platforms it is possible for a zombie process to remain
1122 /// after a kill is sent; to avoid this, the caller should ensure that either
1123 /// `child.wait().await` or `child.try_wait()` is invoked successfully.
1124 pub fn start_kill(&mut self) -> io::Result<()> {
1125 match &mut self.child {
1126 FusedChild::Child(child) => child.kill(),
1127 FusedChild::Done(_) => Err(io::Error::new(
1128 io::ErrorKind::InvalidInput,
1129 "invalid argument: can't kill an exited process",
1130 )),
1131 }
1132 }
1133
1134 /// Forces the child to exit.
1135 ///
1136 /// This is equivalent to sending a `SIGKILL` on unix platforms.
1137 ///
1138 /// If the child has to be killed remotely, it is possible to do it using
1139 /// a combination of the select! macro and a `oneshot` channel. In the following
1140 /// example, the child will run until completion unless a message is sent on
1141 /// the `oneshot` channel. If that happens, the child is killed immediately
1142 /// using the `.kill()` method.
1143 ///
1144 /// ```no_run
1145 /// use tokio::process::Command;
1146 /// use tokio::sync::oneshot::channel;
1147 ///
1148 /// #[tokio::main]
1149 /// async fn main() {
1150 /// let (send, recv) = channel::<()>();
1151 /// let mut child = Command::new("sleep").arg("1").spawn().unwrap();
1152 /// tokio::spawn(async move { send.send(()) });
1153 /// tokio::select! {
1154 /// _ = child.wait() => {}
1155 /// _ = recv => child.kill().await.expect("kill failed"),
1156 /// }
1157 /// }
1158 /// ```
1159 pub async fn kill(&mut self) -> io::Result<()> {
1160 self.start_kill()?;
1161 self.wait().await?;
1162 Ok(())
1163 }
1164
1165 /// Waits for the child to exit completely, returning the status that it
1166 /// exited with. This function will continue to have the same return value
1167 /// after it has been called at least once.
1168 ///
1169 /// The stdin handle to the child process, if any, will be closed
1170 /// before waiting. This helps avoid deadlock: it ensures that the
1171 /// child does not block waiting for input from the parent, while
1172 /// the parent waits for the child to exit.
1173 ///
1174 /// If the caller wishes to explicitly control when the child's stdin
1175 /// handle is closed, they may `.take()` it before calling `.wait()`:
1176 ///
1177 /// # Cancel safety
1178 ///
1179 /// This function is cancel safe.
1180 ///
1181 /// ```
1182 /// # #[cfg(not(unix))]fn main(){}
1183 /// # #[cfg(unix)]
1184 /// use tokio::io::AsyncWriteExt;
1185 /// # #[cfg(unix)]
1186 /// use tokio::process::Command;
1187 /// # #[cfg(unix)]
1188 /// use std::process::Stdio;
1189 ///
1190 /// # #[cfg(unix)]
1191 /// #[tokio::main]
1192 /// async fn main() {
1193 /// let mut child = Command::new("cat")
1194 /// .stdin(Stdio::piped())
1195 /// .spawn()
1196 /// .unwrap();
1197 ///
1198 /// let mut stdin = child.stdin.take().unwrap();
1199 /// tokio::spawn(async move {
1200 /// // do something with stdin here...
1201 /// stdin.write_all(b"hello world\n").await.unwrap();
1202 ///
1203 /// // then drop when finished
1204 /// drop(stdin);
1205 /// });
1206 ///
1207 /// // wait for the process to complete
1208 /// let _ = child.wait().await;
1209 /// }
1210 /// ```
1211 pub async fn wait(&mut self) -> io::Result<ExitStatus> {
1212 // Ensure stdin is closed so the child isn't stuck waiting on
1213 // input while the parent is waiting for it to exit.
1214 drop(self.stdin.take());
1215
1216 match &mut self.child {
1217 FusedChild::Done(exit) => Ok(*exit),
1218 FusedChild::Child(child) => {
1219 let ret = child.await;
1220
1221 if let Ok(exit) = ret {
1222 self.child = FusedChild::Done(exit);
1223 }
1224
1225 ret
1226 }
1227 }
1228 }
1229
1230 /// Attempts to collect the exit status of the child if it has already
1231 /// exited.
1232 ///
1233 /// This function will not block the calling thread and will only
1234 /// check to see if the child process has exited or not. If the child has
1235 /// exited then on Unix the process ID is reaped. This function is
1236 /// guaranteed to repeatedly return a successful exit status so long as the
1237 /// child has already exited.
1238 ///
1239 /// If the child has exited, then `Ok(Some(status))` is returned. If the
1240 /// exit status is not available at this time then `Ok(None)` is returned.
1241 /// If an error occurs, then that error is returned.
1242 ///
1243 /// Note that unlike `wait`, this function will not attempt to drop stdin,
1244 /// nor will it wake the current task if the child exits.
1245 pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
1246 match &mut self.child {
1247 FusedChild::Done(exit) => Ok(Some(*exit)),
1248 FusedChild::Child(guard) => {
1249 let ret = guard.inner.try_wait();
1250
1251 if let Ok(Some(exit)) = ret {
1252 // Avoid the overhead of trying to kill a reaped process
1253 guard.kill_on_drop = false;
1254 self.child = FusedChild::Done(exit);
1255 }
1256
1257 ret
1258 }
1259 }
1260 }
1261
1262 /// Returns a future that will resolve to an `Output`, containing the exit
1263 /// status, stdout, and stderr of the child process.
1264 ///
1265 /// The returned future will simultaneously waits for the child to exit and
1266 /// collect all remaining output on the stdout/stderr handles, returning an
1267 /// `Output` instance.
1268 ///
1269 /// The stdin handle to the child process, if any, will be closed before
1270 /// waiting. This helps avoid deadlock: it ensures that the child does not
1271 /// block waiting for input from the parent, while the parent waits for the
1272 /// child to exit.
1273 ///
1274 /// By default, stdin, stdout and stderr are inherited from the parent. In
1275 /// order to capture the output into this `Output` it is necessary to create
1276 /// new pipes between parent and child. Use `stdout(Stdio::piped())` or
1277 /// `stderr(Stdio::piped())`, respectively, when creating a `Command`.
1278 pub async fn wait_with_output(mut self) -> io::Result<Output> {
1279 use crate::future::try_join3;
1280
1281 async fn read_to_end<A: AsyncRead + Unpin>(io: &mut Option<A>) -> io::Result<Vec<u8>> {
1282 let mut vec = Vec::new();
1283 if let Some(io) = io.as_mut() {
1284 crate::io::util::read_to_end(io, &mut vec).await?;
1285 }
1286 Ok(vec)
1287 }
1288
1289 let mut stdout_pipe = self.stdout.take();
1290 let mut stderr_pipe = self.stderr.take();
1291
1292 let stdout_fut = read_to_end(&mut stdout_pipe);
1293 let stderr_fut = read_to_end(&mut stderr_pipe);
1294
1295 let (status, stdout, stderr) = try_join3(self.wait(), stdout_fut, stderr_fut).await?;
1296
1297 // Drop happens after `try_join` due to <https://github.com/tokio-rs/tokio/issues/4309>
1298 drop(stdout_pipe);
1299 drop(stderr_pipe);
1300
1301 Ok(Output {
1302 status,
1303 stdout,
1304 stderr,
1305 })
1306 }
1307 }
1308
1309 /// The standard input stream for spawned children.
1310 ///
1311 /// This type implements the `AsyncWrite` trait to pass data to the stdin handle of
1312 /// handle of a child process asynchronously.
1313 #[derive(Debug)]
1314 pub struct ChildStdin {
1315 inner: imp::ChildStdio,
1316 }
1317
1318 /// The standard output stream for spawned children.
1319 ///
1320 /// This type implements the `AsyncRead` trait to read data from the stdout
1321 /// handle of a child process asynchronously.
1322 #[derive(Debug)]
1323 pub struct ChildStdout {
1324 inner: imp::ChildStdio,
1325 }
1326
1327 /// The standard error stream for spawned children.
1328 ///
1329 /// This type implements the `AsyncRead` trait to read data from the stderr
1330 /// handle of a child process asynchronously.
1331 #[derive(Debug)]
1332 pub struct ChildStderr {
1333 inner: imp::ChildStdio,
1334 }
1335
1336 impl ChildStdin {
1337 /// Creates an asynchronous `ChildStdin` from a synchronous one.
1338 ///
1339 /// # Errors
1340 ///
1341 /// This method may fail if an error is encountered when setting the pipe to
1342 /// non-blocking mode, or when registering the pipe with the runtime's IO
1343 /// driver.
1344 pub fn from_std(inner: std::process::ChildStdin) -> io::Result<Self> {
1345 Ok(Self {
1346 inner: imp::stdio(inner)?,
1347 })
1348 }
1349 }
1350
1351 impl ChildStdout {
1352 /// Creates an asynchronous `ChildStdout` from a synchronous one.
1353 ///
1354 /// # Errors
1355 ///
1356 /// This method may fail if an error is encountered when setting the pipe to
1357 /// non-blocking mode, or when registering the pipe with the runtime's IO
1358 /// driver.
1359 pub fn from_std(inner: std::process::ChildStdout) -> io::Result<Self> {
1360 Ok(Self {
1361 inner: imp::stdio(inner)?,
1362 })
1363 }
1364 }
1365
1366 impl ChildStderr {
1367 /// Creates an asynchronous `ChildStderr` from a synchronous one.
1368 ///
1369 /// # Errors
1370 ///
1371 /// This method may fail if an error is encountered when setting the pipe to
1372 /// non-blocking mode, or when registering the pipe with the runtime's IO
1373 /// driver.
1374 pub fn from_std(inner: std::process::ChildStderr) -> io::Result<Self> {
1375 Ok(Self {
1376 inner: imp::stdio(inner)?,
1377 })
1378 }
1379 }
1380
1381 impl AsyncWrite for ChildStdin {
1382 fn poll_write(
1383 mut self: Pin<&mut Self>,
1384 cx: &mut Context<'_>,
1385 buf: &[u8],
1386 ) -> Poll<io::Result<usize>> {
1387 Pin::new(&mut self.inner).poll_write(cx, buf)
1388 }
1389
1390 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1391 Pin::new(&mut self.inner).poll_flush(cx)
1392 }
1393
1394 fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1395 Pin::new(&mut self.inner).poll_shutdown(cx)
1396 }
1397
1398 fn poll_write_vectored(
1399 mut self: Pin<&mut Self>,
1400 cx: &mut Context<'_>,
1401 bufs: &[io::IoSlice<'_>],
1402 ) -> Poll<Result<usize, io::Error>> {
1403 Pin::new(&mut self.inner).poll_write_vectored(cx, bufs)
1404 }
1405
1406 fn is_write_vectored(&self) -> bool {
1407 self.inner.is_write_vectored()
1408 }
1409 }
1410
1411 impl AsyncRead for ChildStdout {
1412 fn poll_read(
1413 mut self: Pin<&mut Self>,
1414 cx: &mut Context<'_>,
1415 buf: &mut ReadBuf<'_>,
1416 ) -> Poll<io::Result<()>> {
1417 Pin::new(&mut self.inner).poll_read(cx, buf)
1418 }
1419 }
1420
1421 impl AsyncRead for ChildStderr {
1422 fn poll_read(
1423 mut self: Pin<&mut Self>,
1424 cx: &mut Context<'_>,
1425 buf: &mut ReadBuf<'_>,
1426 ) -> Poll<io::Result<()>> {
1427 Pin::new(&mut self.inner).poll_read(cx, buf)
1428 }
1429 }
1430
1431 impl TryInto<Stdio> for ChildStdin {
1432 type Error = io::Error;
1433
1434 fn try_into(self) -> Result<Stdio, Self::Error> {
1435 imp::convert_to_stdio(self.inner)
1436 }
1437 }
1438
1439 impl TryInto<Stdio> for ChildStdout {
1440 type Error = io::Error;
1441
1442 fn try_into(self) -> Result<Stdio, Self::Error> {
1443 imp::convert_to_stdio(self.inner)
1444 }
1445 }
1446
1447 impl TryInto<Stdio> for ChildStderr {
1448 type Error = io::Error;
1449
1450 fn try_into(self) -> Result<Stdio, Self::Error> {
1451 imp::convert_to_stdio(self.inner)
1452 }
1453 }
1454
1455 #[cfg(unix)]
1456 #[cfg_attr(docsrs, doc(cfg(unix)))]
1457 mod sys {
1458 use std::{
1459 io,
1460 os::unix::io::{AsFd, AsRawFd, BorrowedFd, OwnedFd, RawFd},
1461 };
1462
1463 use super::{ChildStderr, ChildStdin, ChildStdout};
1464
1465 macro_rules! impl_traits {
1466 ($type:ty) => {
1467 impl $type {
1468 /// Convert into [`OwnedFd`].
1469 pub fn into_owned_fd(self) -> io::Result<OwnedFd> {
1470 self.inner.into_owned_fd()
1471 }
1472 }
1473
1474 impl AsRawFd for $type {
1475 fn as_raw_fd(&self) -> RawFd {
1476 self.inner.as_raw_fd()
1477 }
1478 }
1479
1480 impl AsFd for $type {
1481 fn as_fd(&self) -> BorrowedFd<'_> {
1482 unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
1483 }
1484 }
1485 };
1486 }
1487
1488 impl_traits!(ChildStdin);
1489 impl_traits!(ChildStdout);
1490 impl_traits!(ChildStderr);
1491 }
1492
1493 #[cfg(any(windows, docsrs))]
1494 #[cfg_attr(docsrs, doc(cfg(windows)))]
1495 mod windows {
1496 use super::*;
1497 use crate::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, OwnedHandle, RawHandle};
1498
1499 #[cfg(not(docsrs))]
1500 macro_rules! impl_traits {
1501 ($type:ty) => {
1502 impl $type {
1503 /// Convert into [`OwnedHandle`].
1504 pub fn into_owned_handle(self) -> io::Result<OwnedHandle> {
1505 self.inner.into_owned_handle()
1506 }
1507 }
1508
1509 impl AsRawHandle for $type {
1510 fn as_raw_handle(&self) -> RawHandle {
1511 self.inner.as_raw_handle()
1512 }
1513 }
1514
1515 impl AsHandle for $type {
1516 fn as_handle(&self) -> BorrowedHandle<'_> {
1517 unsafe { BorrowedHandle::borrow_raw(self.as_raw_handle()) }
1518 }
1519 }
1520 };
1521 }
1522
1523 #[cfg(docsrs)]
1524 macro_rules! impl_traits {
1525 ($type:ty) => {
1526 impl $type {
1527 /// Convert into [`OwnedHandle`].
1528 pub fn into_owned_handle(self) -> io::Result<OwnedHandle> {
1529 todo!("For doc generation only")
1530 }
1531 }
1532
1533 impl AsRawHandle for $type {
1534 fn as_raw_handle(&self) -> RawHandle {
1535 todo!("For doc generation only")
1536 }
1537 }
1538
1539 impl AsHandle for $type {
1540 fn as_handle(&self) -> BorrowedHandle<'_> {
1541 todo!("For doc generation only")
1542 }
1543 }
1544 };
1545 }
1546
1547 impl_traits!(ChildStdin);
1548 impl_traits!(ChildStdout);
1549 impl_traits!(ChildStderr);
1550 }
1551
1552 #[cfg(all(test, not(loom)))]
1553 mod test {
1554 use super::kill::Kill;
1555 use super::ChildDropGuard;
1556
1557 use futures::future::FutureExt;
1558 use std::future::Future;
1559 use std::io;
1560 use std::pin::Pin;
1561 use std::task::{Context, Poll};
1562
1563 struct Mock {
1564 num_kills: usize,
1565 num_polls: usize,
1566 poll_result: Poll<Result<(), ()>>,
1567 }
1568
1569 impl Mock {
1570 fn new() -> Self {
1571 Self::with_result(Poll::Pending)
1572 }
1573
1574 fn with_result(result: Poll<Result<(), ()>>) -> Self {
1575 Self {
1576 num_kills: 0,
1577 num_polls: 0,
1578 poll_result: result,
1579 }
1580 }
1581 }
1582
1583 impl Kill for Mock {
1584 fn kill(&mut self) -> io::Result<()> {
1585 self.num_kills += 1;
1586 Ok(())
1587 }
1588 }
1589
1590 impl Future for Mock {
1591 type Output = Result<(), ()>;
1592
1593 fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
1594 let inner = Pin::get_mut(self);
1595 inner.num_polls += 1;
1596 inner.poll_result
1597 }
1598 }
1599
1600 #[test]
1601 fn kills_on_drop_if_specified() {
1602 let mut mock = Mock::new();
1603
1604 {
1605 let guard = ChildDropGuard {
1606 inner: &mut mock,
1607 kill_on_drop: true,
1608 };
1609 drop(guard);
1610 }
1611
1612 assert_eq!(1, mock.num_kills);
1613 assert_eq!(0, mock.num_polls);
1614 }
1615
1616 #[test]
1617 fn no_kill_on_drop_by_default() {
1618 let mut mock = Mock::new();
1619
1620 {
1621 let guard = ChildDropGuard {
1622 inner: &mut mock,
1623 kill_on_drop: false,
1624 };
1625 drop(guard);
1626 }
1627
1628 assert_eq!(0, mock.num_kills);
1629 assert_eq!(0, mock.num_polls);
1630 }
1631
1632 #[test]
1633 fn no_kill_if_already_killed() {
1634 let mut mock = Mock::new();
1635
1636 {
1637 let mut guard = ChildDropGuard {
1638 inner: &mut mock,
1639 kill_on_drop: true,
1640 };
1641 let _ = guard.kill();
1642 drop(guard);
1643 }
1644
1645 assert_eq!(1, mock.num_kills);
1646 assert_eq!(0, mock.num_polls);
1647 }
1648
1649 #[test]
1650 fn no_kill_if_reaped() {
1651 let mut mock_pending = Mock::with_result(Poll::Pending);
1652 let mut mock_reaped = Mock::with_result(Poll::Ready(Ok(())));
1653 let mut mock_err = Mock::with_result(Poll::Ready(Err(())));
1654
1655 let waker = futures::task::noop_waker();
1656 let mut context = Context::from_waker(&waker);
1657 {
1658 let mut guard = ChildDropGuard {
1659 inner: &mut mock_pending,
1660 kill_on_drop: true,
1661 };
1662 let _ = guard.poll_unpin(&mut context);
1663
1664 let mut guard = ChildDropGuard {
1665 inner: &mut mock_reaped,
1666 kill_on_drop: true,
1667 };
1668 let _ = guard.poll_unpin(&mut context);
1669
1670 let mut guard = ChildDropGuard {
1671 inner: &mut mock_err,
1672 kill_on_drop: true,
1673 };
1674 let _ = guard.poll_unpin(&mut context);
1675 }
1676
1677 assert_eq!(1, mock_pending.num_kills);
1678 assert_eq!(1, mock_pending.num_polls);
1679
1680 assert_eq!(0, mock_reaped.num_kills);
1681 assert_eq!(1, mock_reaped.num_polls);
1682
1683 assert_eq!(1, mock_err.num_kills);
1684 assert_eq!(1, mock_err.num_polls);
1685 }
1686 }