1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
//! Async child processes on a [`Runtime`].
//!
//! The API has the shape of [`std::process`], like `smol::process`. A [`Command`] builds the
//! process to spawn. The [`Child`] it spawns holds the pipes to the process, [`ChildStdin`],
//! [`ChildStdout`] and [`ChildStderr`], and has futures that wait for the process to exit. Nothing
//! here blocks the thread: when an operation has to wait, the thread can run other tasks.
//!
//! The pipes implement the `AsyncWrite` and `AsyncRead` traits of [`futures-io`], so the extension
//! traits of [`futures`] work on them.
//!
//! # The runtime
//!
//! A child is spawned on a runtime, which [`Command::spawn`], [`Command::status`] and
//! [`Command::output`] take as an argument.
//!
//! On unix, the runtime's reactor watches the pipes to the child. Reads and writes make progress
//! while a thread is running [`Runtime::block_on`] on that runtime. They also make progress while
//! the helper thread runs the runtime, as it does for one from `SharedRuntime::current`. On Linux
//! (with pidfd support), on Apple's platforms and on the BSDs, the reactor also watches for the
//! process to exit, so a wait for the exit makes progress in the same way.
//!
//! On Windows, the reactor cannot watch a pipe. Each read from and write to a pipe runs as blocking
//! work on a thread of the pool of [`unblock()`](crate::unblock()), so it makes progress even
//! while no thread is running `block_on`. The same holds for a wait for the exit on any platform
//! where the reactor cannot watch for it, which includes Windows. That wait runs on a pool of its
//! own: see [waiting for a child](self#waiting-for-a-child).
//!
//! `Child` and the pipes are generic over the runtime's flavour, on every platform. A child spawned
//! on a [`LocalRuntime`] is a `Child<Local>` (`Local` is the default). It stays on the thread that
//! created it, with its pipes. A child spawned on a [`SharedRuntime`] is a `Child<Shared>`, which
//! can be sent to and used from any thread.
//!
//! # Waiting for a child
//!
//! [`Child::status`] waits for the process to exit and resolves to its exit status.
//! [`Child::output`] does the same after it has read the output pipes.
//!
//! On unix, a process that has exited stays in the process table as a zombie, and keeps its
//! process ID, until its status is collected. [`Child::status`] collects the status when it
//! resolves, and so does [`Child::try_status`], which never waits.
//!
//! If the runtime can watch for the exit, the wait holds no thread:
//!
//! - On Linux, the runtime watches a pidfd, a descriptor of the process that becomes readable when
//! the process exits.
//! - On Apple's platforms and the BSDs, it watches a kqueue that belongs to the child alone, with a
//! filter on the process. The descriptor of the queue becomes readable when the process exits.
//!
//! The reactor watches the descriptor like a pipe, from the spawn until it reports the exit.
//! Dropping the future of a wait leaves nothing running.
//!
//! On Apple's platforms and the BSDs, there is no other way to wait. If the kqueue cannot be
//! created, for example because the process is out of descriptors, the spawn fails with that
//! error, as it does if a pipe cannot be created. On Linux, a process that another process traces
//! cannot be collected after it exits until its tracer lets it go. A wait that finds the process in
//! that state continues on the pool described next.
//!
//! The runtime cannot watch for the exit on Android, on Windows, on other unix systems, and on a
//! Linux without pidfd support (before 5.3, or in a sandbox that rejects the call). There, the wait
//! runs as blocking work on a thread of a pool kept for waits for children, and holds that thread
//! until the process exits. The first wait that finds the process still running starts the work.
//! Spawning does not, so a child that nobody waits for holds no thread. Dropping the future of a
//! wait gives up the wait but not the thread. The next wait for the same child takes it up where it
//! left off, so abandoned waits do not pile up threads.
//!
//! The pool is separate from the one behind [`unblock()`](crate::unblock()). Otherwise a program
//! that waits for many long-running children at once would fill that pool, and all its other
//! blocking work would wait behind them. A [dropped child](self#dropping-a-child) is collected on
//! the same pool.
//!
//! # Dropping a child
//!
//! Dropping a [`Child`] closes the pipes it still holds. It leaves the process running, as
//! dropping a std `Child` does. [`Command::kill_on_drop`] kills the process instead.
//!
//! On unix, a process that exits with nobody to collect its status stays a zombie, and std's
//! `Child` leaves it so. By default, a `Child` that is dropped while its process is running hands
//! the process to a thread of the pool for waits for children. That thread waits for the process
//! to exit and collects its status. [`Command::reap_on_drop`] turns this off.
//!
//! Each such thread is held until its process exits, so dropping many long-running children holds
//! as many threads. The pool has room for 500 threads. Beyond that, a dropped child waits for a
//! free thread, and stays a zombie if it exits before one is free. Killing the processes, waiting
//! for them, or turning `reap_on_drop` off keeps threads from being held for long.
//!
//! The threads are named `zruntime child wait`. The pool is separate from the one behind
//! [`unblock()`](crate::unblock()), which all other blocking work shares. However many children
//! are dropped, and however long they run, that work never waits behind them.
//!
//! Windows leaves no zombie, so there is nothing to collect there, and `reap_on_drop` does
//! nothing.
//!
//! # Example
//!
//! Runs a command on a local runtime and checks its output:
//!
//! ```
//! # #[cfg(unix)]
//! # fn main() -> std::io::Result<()> {
//! use zruntime::{LocalRuntime, process::Command};
//!
//! let runtime = LocalRuntime::new()?;
//!
//! let output = runtime.block_on(Command::new("echo").arg("hello").output(&runtime))?;
//!
//! assert!(output.status.success());
//! assert_eq!(output.stdout, b"hello\n");
//! # Ok(())
//! # }
//! # #[cfg(not(unix))]
//! # fn main() {}
//! ```
//!
//! [`futures-io`]: https://docs.rs/futures-io
//! [`futures`]: https://docs.rs/futures
//! [`LocalRuntime`]: crate::LocalRuntime
//! [`Runtime`]: crate::Runtime
//! [`Runtime::block_on`]: crate::Runtime::block_on
//! [`SharedRuntime`]: crate::SharedRuntime
use ;
use AsyncRead;
use Exit;
pub use ;
use crate::;
pub use ;
/// A builder for a process to spawn, like [`std::process::Command`].
///
/// The methods that spawn the process take the runtime to spawn it on. Configure the command as
/// with std: its arguments, environment, working directory and the standard streams of the
/// process. A command from `Command::new` starts with the environment and working directory of
/// this process.
///
/// [`as_std`](Command::as_std) gives the std command inside, for its getters of the program, the
/// arguments, the environment and the working directory.
/// [`as_std_mut`](Command::as_std_mut) gives it for the extension traits of the platform, such as
/// std's `CommandExt` on unix.
///
/// What happens to the process when its [`Child`] is dropped is set on this builder, not on the
/// std command. [`kill_on_drop`](Command::kill_on_drop) and
/// [`reap_on_drop`](Command::reap_on_drop) set it, and
/// [`get_kill_on_drop`](Command::get_kill_on_drop) and
/// [`get_reap_on_drop`](Command::get_reap_on_drop) read it.
///
/// A command can run more than once. A standard stream that was not configured gets the default of
/// the method that runs the command, afresh on each run. [`spawn`](Command::spawn) and
/// [`status`](Command::status) inherit it from this process. [`output`](Command::output) connects
/// the standard input to nothing and the other two streams to pipes, which it reads to their ends.
///
/// `spawn`, `status` and `output` start the process when they are called, before any future is
/// polled, and it runs from then on. The futures of `status` and `output` only wait for it. If the
/// spawn fails, `spawn` returns the error, and the other two resolve to it.
///
/// # Example
///
/// Runs a command and checks its exit status. Its output goes to this process's own:
///
/// ```
/// # #[cfg(unix)]
/// # fn main() -> std::io::Result<()> {
/// use zruntime::{LocalRuntime, process::Command};
///
/// let runtime = LocalRuntime::new()?;
///
/// let status = runtime.block_on(Command::new("true").status(&runtime))?;
///
/// assert!(status.success());
/// # Ok(())
/// # }
/// # #[cfg(not(unix))]
/// # fn main() {}
/// ```
/// Wraps a std command.
///
/// The standard streams configured on `command` count as not configured, so the method that runs
/// the command overrides them with its defaults. As with [`Command::new`], the process is not
/// killed when its [`Child`] is dropped, and its status is collected where the platform needs
/// that.
/// A spawned child process, with the pipes to it that its command asked for.
///
/// [`Command::spawn`] creates it on a runtime. A `Child<Local>` (`Local` is the default) stays on
/// the thread that created it, and a `Child<Shared>` can be sent to and used from any thread. See
/// the [module documentation](self) for what drives it.
///
/// The pipes are public fields. Each is `Some` if the command asked for it with `Stdio::piped()`,
/// and `None` otherwise. To move a pipe elsewhere, take it out, as in `child.stdout.take()` or
/// `let Child { stdout, .. } = child;`. `Child` has no `Drop` implementation, so this works for
/// every field.
///
/// Dropping a `Child` leaves the process running unless the command said otherwise: see the
/// [module documentation](self#dropping-a-child).
///
/// # Example
///
/// Reads the output of a child as it is written, then waits for its exit status:
///
/// ```
/// # #[cfg(unix)]
/// # fn main() -> std::io::Result<()> {
/// use futures::AsyncReadExt;
/// use zruntime::{
/// LocalRuntime,
/// process::{Command, Stdio},
/// };
///
/// let runtime = LocalRuntime::new()?;
///
/// runtime.block_on(async {
/// let mut child = Command::new("echo")
/// .arg("hello")
/// .stdout(Stdio::piped())
/// .spawn(&runtime)?;
///
/// let mut greeting = String::new();
/// let mut stdout = child.stdout.take().expect("stdout is piped");
/// stdout.read_to_string(&mut greeting).await?;
///
/// assert_eq!(greeting, "hello\n");
/// assert!(child.status().await?.success());
/// # Ok::<_, std::io::Error>(())
/// })?;
/// # Ok(())
/// # }
/// # #[cfg(not(unix))]
/// # fn main() {}
/// ```
/// The std child, and what is to be done with its process when the `Child` is dropped.
///
/// A guard of its own rather than a `Drop` of `Child`, which would keep the pipes from being moved
/// out of the `Child` by the code that holds it.
/// Sees to it that the status of `child`'s process is collected, once it has exited.
///
/// A process that has exited already is collected by the look at it. One that is still running is
/// handed to a thread of [`WAITS`], which waits for it to exit, and nothing awaits the outcome: the
/// thread collects the status and that is all.
/// A process that exits leaves no status on Windows to be collected, so there is nothing to do.
/// The pool that the waits for children run on, apart from that of
/// [`unblock()`](crate::unblock()): the waits that reap a child that is dropped while its process
/// runs, and, where the runtime cannot watch for the exit of a child, the waits for it.
///
/// A wait for a child holds its thread for as long as the child runs, which may be as long as the
/// program does. Such waits are not the work the pool of `unblock()` is for, which ends of its own
/// accord, and a program that lets go of enough children, or waits for enough of them at once,
/// would hold every thread of that pool with them, for every other piece of blocking work to wait
/// behind. So they have a pool of their own, whose threads hold nothing else: it holds a thread for
/// each wait that runs, up to [`MAX_THREADS`], and past that a wait waits its turn behind the other
/// waits for children, never behind other blocking work. Its threads are named
/// `zruntime child wait`. A child that is dropped after a wait for its exit was given up on holds
/// two of them until its process exits: that of the wait, which runs on, and that of the reap.
static WAITS: Pool = new;
/// What [`Child::output`] reads one of the child's pipes into.
/// How much a read of a pipe takes at most: as much as the reads of `Unblock` do by default.
const CHUNK: usize = 8 * 1024;