Coverage Report

Created: 2025-02-25 06:39

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