Skip to main content

portable_pty/
lib.rs

1//! This crate provides a cross platform API for working with the
2//! psuedo terminal (pty) interfaces provided by the system.
3//! Unlike other crates in this space, this crate provides a set
4//! of traits that allow selecting from different implementations
5//! at runtime.
6//! This crate is part of [wezterm](https://github.com/wezterm/wezterm).
7//!
8//! ```no_run
9//! use portable_pty::{CommandBuilder, PtySize, native_pty_system, PtySystem};
10//! use anyhow::Error;
11//!
12//! // Use the native pty implementation for the system
13//! let pty_system = native_pty_system();
14//!
15//! // Create a new pty
16//! let mut pair = pty_system.openpty(PtySize {
17//!     rows: 24,
18//!     cols: 80,
19//!     // Not all systems support pixel_width, pixel_height,
20//!     // but it is good practice to set it to something
21//!     // that matches the size of the selected font.  That
22//!     // is more complex than can be shown here in this
23//!     // brief example though!
24//!     pixel_width: 0,
25//!     pixel_height: 0,
26//! })?;
27//!
28//! // Spawn a shell into the pty
29//! let cmd = CommandBuilder::new("bash");
30//! let child = pair.slave.spawn_command(cmd)?;
31//!
32//! // Read and parse output from the pty with reader
33//! let mut reader = pair.master.try_clone_reader()?;
34//!
35//! // Send data to the pty by writing to the master
36//! writeln!(pair.master.take_writer()?, "ls -l\r\n")?;
37//! # Ok::<(), Error>(())
38//! ```
39//!
40use anyhow::Error;
41use downcast_rs::{impl_downcast, Downcast};
42#[cfg(feature = "serde_support")]
43use serde_derive::*;
44use std::io::Result as IoResult;
45#[cfg(windows)]
46use std::os::windows::prelude::{AsRawHandle, RawHandle};
47
48/// A PTY child whose exclusive reap ownership can be transferred to sysprims.
49///
50/// Callers receive this type only after a containment guard has finalized.
51/// While containment is active, the guard keeps the child handle private.
52#[derive(Debug)]
53pub struct ContainedPtyChild {
54    #[cfg(unix)]
55    pub(crate) child: std::process::Child,
56    #[cfg(windows)]
57    pub(crate) child: win::WinChild,
58}
59
60impl ContainedPtyChild {
61    #[cfg(unix)]
62    pub(crate) fn new(child: std::process::Child) -> Self {
63        Self { child }
64    }
65
66    #[cfg(windows)]
67    pub(crate) fn new(child: win::WinChild) -> Self {
68        Self { child }
69    }
70}
71
72/// Stage at which a guarded PTY spawn failed.
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum ContainedPtySpawnErrorStage {
75    /// No child was created.
76    BeforeSpawn,
77    /// Spawn-time group/Job assignment evidence could not be sealed.
78    Receipt,
79    /// The exact child and receipt could not be adopted into a guard.
80    Adoption,
81    /// The assigned child could not be resumed and was resolved through its Job.
82    Resume,
83}
84
85enum FailedChildRecoveryCommand {
86    Adopt(ContainedPtyChild),
87    Attempt {
88        timeout: std::time::Duration,
89        #[cfg(test)]
90        fault: FailedChildRecoveryFault,
91        response: std::sync::mpsc::SyncSender<IoResult<bool>>,
92    },
93}
94
95#[cfg(test)]
96#[derive(Clone, Copy)]
97enum FailedChildRecoveryFault {
98    None,
99    #[cfg(unix)]
100    KillError,
101    #[cfg(unix)]
102    Deadline,
103}
104
105struct FailedChildRecovery {
106    sender: std::sync::mpsc::Sender<FailedChildRecoveryCommand>,
107    pending: std::sync::Arc<std::sync::atomic::AtomicBool>,
108}
109
110impl FailedChildRecovery {
111    fn prepare() -> IoResult<Self> {
112        let (sender, receiver) = std::sync::mpsc::channel();
113        let pending = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
114        let worker_pending = std::sync::Arc::clone(&pending);
115        std::thread::Builder::new()
116            .name("sysprims-pty-recovery".to_string())
117            .spawn(move || failed_child_recovery_worker(receiver, worker_pending))?;
118        Ok(Self { sender, pending })
119    }
120
121    fn attach(&self, child: ContainedPtyChild) {
122        self.pending
123            .store(true, std::sync::atomic::Ordering::Release);
124        if let Err(error) = self.sender.send(FailedChildRecoveryCommand::Adopt(child)) {
125            let child = match error.0 {
126                FailedChildRecoveryCommand::Adopt(child) => child,
127                FailedChildRecoveryCommand::Attempt { .. } => unreachable!(),
128            };
129            bounded_local_recovery_or_abort(child);
130        }
131    }
132
133    fn attempt(&self, timeout: std::time::Duration) -> IoResult<bool> {
134        self.attempt_inner(
135            timeout,
136            #[cfg(test)]
137            FailedChildRecoveryFault::None,
138        )
139    }
140
141    fn attempt_inner(
142        &self,
143        timeout: std::time::Duration,
144        #[cfg(test)] fault: FailedChildRecoveryFault,
145    ) -> IoResult<bool> {
146        if !self.pending.load(std::sync::atomic::Ordering::Acquire) {
147            return Ok(true);
148        }
149
150        let timeout = timeout.min(std::time::Duration::from_secs(2));
151        let (response, result) = std::sync::mpsc::sync_channel(1);
152        self.sender
153            .send(FailedChildRecoveryCommand::Attempt {
154                timeout,
155                #[cfg(test)]
156                fault,
157                response,
158            })
159            .map_err(|_| {
160                std::io::Error::new(
161                    std::io::ErrorKind::BrokenPipe,
162                    "exact-child recovery owner stopped",
163                )
164            })?;
165        result
166            .recv_timeout(timeout + std::time::Duration::from_millis(250))
167            .map_err(|error| {
168                std::io::Error::new(
169                    std::io::ErrorKind::TimedOut,
170                    format!("exact-child recovery response unavailable: {error}"),
171                )
172            })?
173    }
174
175    #[cfg(all(test, unix))]
176    fn attempt_with_fault(
177        &self,
178        timeout: std::time::Duration,
179        fault: FailedChildRecoveryFault,
180    ) -> IoResult<bool> {
181        self.attempt_inner(timeout, fault)
182    }
183
184    fn is_pending(&self) -> bool {
185        self.pending.load(std::sync::atomic::Ordering::Acquire)
186    }
187}
188
189fn failed_child_recovery_worker(
190    receiver: std::sync::mpsc::Receiver<FailedChildRecoveryCommand>,
191    pending: std::sync::Arc<std::sync::atomic::AtomicBool>,
192) {
193    let mut child = None;
194    while let Ok(command) = receiver.recv() {
195        match command {
196            FailedChildRecoveryCommand::Adopt(adopted) => {
197                debug_assert!(child.is_none());
198                child = Some(adopted);
199            }
200            FailedChildRecoveryCommand::Attempt {
201                timeout,
202                #[cfg(test)]
203                fault,
204                response,
205            } => {
206                let result = attempt_failed_child_recovery(
207                    &mut child,
208                    timeout,
209                    #[cfg(test)]
210                    fault,
211                );
212                pending.store(child.is_some(), std::sync::atomic::Ordering::Release);
213                let _ = response.send(result);
214            }
215        }
216    }
217
218    // Disconnect means the public error/controller was dropped. Ownership
219    // stays on this parent-side worker; the destructor itself never blocks.
220    while child.is_some() {
221        let _ = attempt_failed_child_recovery(
222            &mut child,
223            std::time::Duration::from_secs(2),
224            #[cfg(test)]
225            FailedChildRecoveryFault::None,
226        );
227        pending.store(child.is_some(), std::sync::atomic::Ordering::Release);
228        if child.is_some() {
229            std::thread::sleep(std::time::Duration::from_millis(10));
230        }
231    }
232}
233
234fn attempt_failed_child_recovery(
235    child: &mut Option<ContainedPtyChild>,
236    timeout: std::time::Duration,
237    #[cfg(test)] fault: FailedChildRecoveryFault,
238) -> IoResult<bool> {
239    let owned_child = match child.as_mut() {
240        Some(child) => child,
241        None => return Ok(true),
242    };
243
244    if Child::try_wait(owned_child)?.is_some() {
245        child.take();
246        return Ok(true);
247    }
248
249    #[cfg(test)]
250    match fault {
251        #[cfg(unix)]
252        FailedChildRecoveryFault::KillError => {
253            return Err(std::io::Error::new(
254                std::io::ErrorKind::PermissionDenied,
255                "injected exact-child kill failure",
256            ));
257        }
258        #[cfg(unix)]
259        FailedChildRecoveryFault::Deadline => {
260            std::thread::sleep(timeout.min(std::time::Duration::from_millis(10)));
261            return Ok(false);
262        }
263        FailedChildRecoveryFault::None => {}
264    }
265
266    // This is the exact spawn-owned child handle. Never
267    // reconstruct signal authority from an observed PID.
268    ChildKiller::kill(owned_child)?;
269
270    let timeout = timeout.min(std::time::Duration::from_secs(2));
271    let deadline = std::time::Instant::now() + timeout;
272    loop {
273        match Child::try_wait(owned_child)? {
274            Some(_) => {
275                child.take();
276                return Ok(true);
277            }
278            None if std::time::Instant::now() < deadline => {
279                std::thread::sleep(std::time::Duration::from_millis(10));
280            }
281            None => return Ok(false),
282        }
283    }
284}
285
286fn bounded_local_recovery_or_abort(mut child: ContainedPtyChild) -> ! {
287    let _ = ChildKiller::kill(&mut child);
288    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
289    loop {
290        match Child::try_wait(&mut child) {
291            Ok(Some(_)) => {
292                std::process::abort();
293            }
294            Ok(None) if std::time::Instant::now() < deadline => {
295                std::thread::sleep(std::time::Duration::from_millis(10));
296            }
297            Ok(None) | Err(_) => std::process::abort(),
298        }
299    }
300}
301
302/// Error from a guarded PTY spawn.
303///
304/// Errors after child creation retain an opaque exact-child recovery state.
305/// The active child handle is never returned to the caller or discarded.
306/// Dropping an error disconnects its bounded controller; a parent-side worker
307/// keeps exact-child ownership through direct kill and reap.
308pub struct ContainedPtySpawnError {
309    stage: ContainedPtySpawnErrorStage,
310    source: Error,
311    recovery: Option<FailedChildRecovery>,
312}
313
314impl ContainedPtySpawnError {
315    pub(crate) fn before_spawn(source: Error) -> Self {
316        Self {
317            stage: ContainedPtySpawnErrorStage::BeforeSpawn,
318            source,
319            recovery: None,
320        }
321    }
322
323    pub(crate) fn after_spawn(
324        stage: ContainedPtySpawnErrorStage,
325        source: Error,
326        child: ContainedPtyChild,
327        recovery: FailedChildRecovery,
328    ) -> Self {
329        debug_assert!(stage != ContainedPtySpawnErrorStage::BeforeSpawn);
330        recovery.attach(child);
331        let mut error = Self {
332            stage,
333            source,
334            recovery: Some(recovery),
335        };
336        let _ = error.recover(std::time::Duration::from_secs(2));
337        error
338    }
339
340    #[cfg(all(test, unix))]
341    pub(crate) fn after_spawn_pending_for_test(
342        stage: ContainedPtySpawnErrorStage,
343        source: Error,
344        child: ContainedPtyChild,
345        recovery: FailedChildRecovery,
346    ) -> Self {
347        debug_assert!(stage != ContainedPtySpawnErrorStage::BeforeSpawn);
348        recovery.attach(child);
349        Self {
350            stage,
351            source,
352            recovery: Some(recovery),
353        }
354    }
355
356    /// Report the stage at which the spawn failed.
357    pub fn stage(&self) -> ContainedPtySpawnErrorStage {
358        self.stage
359    }
360
361    /// Whether exact-child recovery is still in progress.
362    pub fn recovery_pending(&self) -> bool {
363        self.recovery
364            .as_ref()
365            .is_some_and(FailedChildRecovery::is_pending)
366    }
367
368    /// Make one bounded exact-child recovery attempt.
369    ///
370    /// The attempt is capped at two seconds. Returns `true` when no child
371    /// remains to reap.
372    pub fn recover(&mut self, timeout: std::time::Duration) -> IoResult<bool> {
373        match self.recovery.as_mut() {
374            Some(recovery) => recovery.attempt(timeout),
375            None => Ok(true),
376        }
377    }
378}
379
380impl std::fmt::Debug for ContainedPtySpawnError {
381    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
382        formatter
383            .debug_struct("ContainedPtySpawnError")
384            .field("stage", &self.stage)
385            .field("source", &self.source)
386            .field("recovery_pending", &self.recovery_pending())
387            .finish()
388    }
389}
390
391impl std::fmt::Display for ContainedPtySpawnError {
392    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
393        self.source.fmt(formatter)
394    }
395}
396
397impl std::error::Error for ContainedPtySpawnError {
398    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
399        Some(self.source.as_ref())
400    }
401}
402
403/// An owned, spawn-time-acquired PTY containment capability.
404pub type ContainedPtyGuard = sysprims_timeout::ContainmentGuard<ContainedPtyChild>;
405
406pub mod cmdbuilder;
407pub use cmdbuilder::CommandBuilder;
408
409#[cfg(unix)]
410pub mod unix;
411#[cfg(windows)]
412pub mod win;
413
414pub mod serial;
415
416/// Represents the size of the visible display area in the pty
417#[derive(Debug, Clone, Copy, PartialEq, Eq)]
418#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
419pub struct PtySize {
420    /// The number of lines of text
421    pub rows: u16,
422    /// The number of columns of text
423    pub cols: u16,
424    /// The width of a cell in pixels.  Note that some systems never
425    /// fill this value and ignore it.
426    pub pixel_width: u16,
427    /// The height of a cell in pixels.  Note that some systems never
428    /// fill this value and ignore it.
429    pub pixel_height: u16,
430}
431
432impl Default for PtySize {
433    fn default() -> Self {
434        PtySize {
435            rows: 24,
436            cols: 80,
437            pixel_width: 0,
438            pixel_height: 0,
439        }
440    }
441}
442
443/// Represents the master/control end of the pty
444pub trait MasterPty: Downcast + Send {
445    /// Inform the kernel and thus the child process that the window resized.
446    /// It will update the winsize information maintained by the kernel,
447    /// and generate a signal for the child to notice and update its state.
448    fn resize(&self, size: PtySize) -> Result<(), Error>;
449    /// Retrieves the size of the pty as known by the kernel
450    fn get_size(&self) -> Result<PtySize, Error>;
451    /// Obtain a readable handle; output from the slave(s) is readable
452    /// via this stream.
453    fn try_clone_reader(&self) -> Result<Box<dyn std::io::Read + Send>, Error>;
454    /// Obtain a writable handle; writing to it will send data to the
455    /// slave end.
456    /// Dropping the writer will send EOF to the slave end.
457    /// It is invalid to take the writer more than once.
458    fn take_writer(&self) -> Result<Box<dyn std::io::Write + Send>, Error>;
459
460    /// If applicable to the type of the tty, return the local process id
461    /// of the process group or session leader
462    #[cfg(unix)]
463    fn process_group_leader(&self) -> Option<libc::pid_t>;
464
465    /// If get_termios() and process_group_leader() are both implemented and
466    /// return Some, then as_raw_fd() should return the same underlying fd
467    /// associated with the stream. This is to enable applications that
468    /// "know things" to query similar information for themselves.
469    #[cfg(unix)]
470    fn as_raw_fd(&self) -> Option<unix::RawFd>;
471
472    #[cfg(unix)]
473    fn tty_name(&self) -> Option<std::path::PathBuf>;
474
475    /// If applicable to the type of the tty, return the termios
476    /// associated with the stream
477    #[cfg(unix)]
478    fn get_termios(&self) -> Option<nix::sys::termios::Termios> {
479        None
480    }
481}
482impl_downcast!(MasterPty);
483
484/// Represents a child process spawned into the pty.
485/// This handle can be used to wait for or terminate that child process.
486pub trait Child: std::fmt::Debug + ChildKiller + Downcast + Send {
487    /// Poll the child to see if it has completed.
488    /// Does not block.
489    /// Returns None if the child has not yet terminated,
490    /// else returns its exit status.
491    fn try_wait(&mut self) -> IoResult<Option<ExitStatus>>;
492    /// Blocks execution until the child process has completed,
493    /// yielding its exit status.
494    fn wait(&mut self) -> IoResult<ExitStatus>;
495    /// Returns the process identifier of the child process,
496    /// if applicable
497    fn process_id(&self) -> Option<u32>;
498    /// Returns the process handle of the child process, if applicable.
499    /// Only available on Windows.
500    #[cfg(windows)]
501    fn as_raw_handle(&self) -> Option<std::os::windows::io::RawHandle>;
502}
503impl_downcast!(Child);
504
505/// Represents the ability to signal a Child to terminate
506pub trait ChildKiller: std::fmt::Debug + Downcast + Send {
507    /// Terminate the child process
508    fn kill(&mut self) -> IoResult<()>;
509
510    /// Clone an object that can be split out from the Child in order
511    /// to send it signals independently from a thread that may be
512    /// blocked in `.wait`.
513    fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync>;
514}
515impl_downcast!(ChildKiller);
516
517/// Represents the slave side of a pty.
518/// Can be used to spawn processes into the pty.
519pub trait SlavePty {
520    /// Spawns the command specified by the provided CommandBuilder
521    fn spawn_command(&self, cmd: CommandBuilder) -> Result<Box<dyn Child + Send + Sync>, Error>;
522
523    /// Spawns a command with a sealed same-spawn sysprims containment guard.
524    ///
525    /// Native Unix PTYs use a sealed session receipt. Native Windows ConPTY
526    /// creates the child suspended and seals exact-process Job membership
527    /// before one resume. Other PTY implementations reject before spawning.
528    fn spawn_contained_command(
529        &self,
530        cmd: CommandBuilder,
531    ) -> Result<ContainedPtyGuard, ContainedPtySpawnError> {
532        let _ = cmd;
533        Err(ContainedPtySpawnError::before_spawn(anyhow::anyhow!(
534            "spawn-time PTY containment is unavailable for this PTY implementation"
535        )))
536    }
537}
538
539/// Represents the exit status of a child process.
540#[derive(Debug, Clone)]
541pub struct ExitStatus {
542    code: u32,
543    signal: Option<String>,
544}
545
546impl ExitStatus {
547    /// Construct an ExitStatus from a process return code
548    pub fn with_exit_code(code: u32) -> Self {
549        Self { code, signal: None }
550    }
551
552    /// Construct an ExitStatus from a signal name
553    pub fn with_signal(signal: &str) -> Self {
554        Self {
555            code: 1,
556            signal: Some(signal.to_string()),
557        }
558    }
559
560    /// Returns true if the status indicates successful completion
561    pub fn success(&self) -> bool {
562        match self.signal {
563            None => self.code == 0,
564            Some(_) => false,
565        }
566    }
567
568    /// Returns the exit code that this ExitStatus was constructed with
569    pub fn exit_code(&self) -> u32 {
570        self.code
571    }
572
573    /// Returns the signal if present that this ExitStatus was constructed with
574    pub fn signal(&self) -> Option<&str> {
575        self.signal.as_deref()
576    }
577}
578
579impl From<std::process::ExitStatus> for ExitStatus {
580    fn from(status: std::process::ExitStatus) -> ExitStatus {
581        #[cfg(unix)]
582        {
583            use std::os::unix::process::ExitStatusExt;
584
585            if let Some(signal) = status.signal() {
586                let signame = unsafe { libc::strsignal(signal) };
587                let signal = if signame.is_null() {
588                    format!("Signal {signal}")
589                } else {
590                    let signame = unsafe { std::ffi::CStr::from_ptr(signame) };
591                    signame.to_string_lossy().to_string()
592                };
593
594                return ExitStatus {
595                    code: status.code().map(|c| c as u32).unwrap_or(1),
596                    signal: Some(signal),
597                };
598            }
599        }
600
601        let code =
602            status
603                .code()
604                .map(|c| c as u32)
605                .unwrap_or_else(|| if status.success() { 0 } else { 1 });
606
607        ExitStatus { code, signal: None }
608    }
609}
610
611impl std::fmt::Display for ExitStatus {
612    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
613        if self.success() {
614            write!(fmt, "Success")
615        } else {
616            match &self.signal {
617                Some(sig) => write!(fmt, "Terminated by {sig}"),
618                None => write!(fmt, "Exited with code {}", self.code),
619            }
620        }
621    }
622}
623
624pub struct PtyPair {
625    // slave is listed first so that it is dropped first.
626    // The drop order is stable and specified by rust rfc 1857
627    pub slave: Box<dyn SlavePty + Send>,
628    pub master: Box<dyn MasterPty + Send>,
629}
630
631/// The `PtySystem` trait allows an application to work with multiple
632/// possible Pty implementations at runtime.  This is important on
633/// Windows systems which have a variety of implementations.
634pub trait PtySystem: Downcast {
635    /// Create a new Pty instance with the window size set to the specified
636    /// dimensions.  Returns a (master, slave) Pty pair.  The master side
637    /// is used to drive the slave side.
638    fn openpty(&self, size: PtySize) -> anyhow::Result<PtyPair>;
639}
640impl_downcast!(PtySystem);
641
642impl Child for std::process::Child {
643    fn try_wait(&mut self) -> IoResult<Option<ExitStatus>> {
644        std::process::Child::try_wait(self).map(|status| status.map(Into::into))
645    }
646
647    fn wait(&mut self) -> IoResult<ExitStatus> {
648        std::process::Child::wait(self).map(Into::into)
649    }
650
651    fn process_id(&self) -> Option<u32> {
652        Some(self.id())
653    }
654
655    #[cfg(windows)]
656    fn as_raw_handle(&self) -> Option<std::os::windows::io::RawHandle> {
657        Some(std::os::windows::io::AsRawHandle::as_raw_handle(self))
658    }
659}
660
661impl Child for ContainedPtyChild {
662    fn try_wait(&mut self) -> IoResult<Option<ExitStatus>> {
663        #[cfg(unix)]
664        return std::process::Child::try_wait(&mut self.child).map(|status| status.map(Into::into));
665
666        #[cfg(windows)]
667        return Child::try_wait(&mut self.child);
668    }
669
670    fn wait(&mut self) -> IoResult<ExitStatus> {
671        #[cfg(unix)]
672        return std::process::Child::wait(&mut self.child).map(Into::into);
673
674        #[cfg(windows)]
675        return Child::wait(&mut self.child);
676    }
677
678    fn process_id(&self) -> Option<u32> {
679        #[cfg(unix)]
680        return Some(self.child.id());
681
682        #[cfg(windows)]
683        return Child::process_id(&self.child);
684    }
685
686    #[cfg(windows)]
687    fn as_raw_handle(&self) -> Option<std::os::windows::io::RawHandle> {
688        Child::as_raw_handle(&self.child)
689    }
690}
691
692impl sysprims_timeout::ContainmentChild for ContainedPtyChild {
693    fn process_id(&self) -> Option<u32> {
694        Child::process_id(self)
695    }
696
697    fn try_wait(&mut self) -> IoResult<bool> {
698        Child::try_wait(self).map(|status| status.is_some())
699    }
700
701    #[cfg(windows)]
702    fn raw_process_handle(&self) -> Option<std::os::windows::io::RawHandle> {
703        Child::as_raw_handle(self)
704    }
705}
706
707#[derive(Debug)]
708struct ProcessSignaller {
709    pid: Option<u32>,
710
711    #[cfg(windows)]
712    handle: Option<filedescriptor::OwnedHandle>,
713}
714
715#[cfg(windows)]
716impl ChildKiller for ProcessSignaller {
717    fn kill(&mut self) -> IoResult<()> {
718        if let Some(handle) = &self.handle {
719            unsafe {
720                if winapi::um::processthreadsapi::TerminateProcess(handle.as_raw_handle() as _, 127)
721                    == 0
722                {
723                    return Err(std::io::Error::last_os_error());
724                }
725            }
726        }
727        Ok(())
728    }
729    fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
730        Box::new(Self {
731            pid: self.pid,
732            handle: self.handle.as_ref().and_then(|h| h.try_clone().ok()),
733        })
734    }
735}
736
737#[cfg(unix)]
738impl ChildKiller for ProcessSignaller {
739    fn kill(&mut self) -> IoResult<()> {
740        if let Some(pid) = self.pid {
741            let result = unsafe { libc::kill(pid as i32, libc::SIGHUP) };
742            if result != 0 {
743                return Err(std::io::Error::last_os_error());
744            }
745        }
746        Ok(())
747    }
748
749    fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
750        Box::new(Self { pid: self.pid })
751    }
752}
753
754impl ChildKiller for std::process::Child {
755    fn kill(&mut self) -> IoResult<()> {
756        #[cfg(unix)]
757        {
758            // On unix, we send the SIGHUP signal instead of trying to kill
759            // the process. The default behavior of a process receiving this
760            // signal is to be killed unless it configured a signal handler.
761            let result = unsafe { libc::kill(self.id() as i32, libc::SIGHUP) };
762            if result != 0 {
763                return Err(std::io::Error::last_os_error());
764            }
765
766            // We successfully delivered SIGHUP, but the semantics of Child::kill
767            // are that on success the process is dead or shortly about to
768            // terminate.  Since SIGUP doesn't guarantee termination, we
769            // give the process a bit of a grace period to shutdown or do whatever
770            // it is doing in its signal handler befre we proceed with the
771            // full on kill.
772            for attempt in 0..5 {
773                if attempt > 0 {
774                    std::thread::sleep(std::time::Duration::from_millis(50));
775                }
776
777                if let Ok(Some(_)) = self.try_wait() {
778                    // It completed, so report success!
779                    return Ok(());
780                }
781            }
782
783            // it's still alive after a grace period, so proceed with a kill
784        }
785
786        std::process::Child::kill(self)
787    }
788
789    #[cfg(windows)]
790    fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
791        struct RawDup(RawHandle);
792        impl AsRawHandle for RawDup {
793            fn as_raw_handle(&self) -> RawHandle {
794                self.0
795            }
796        }
797
798        Box::new(ProcessSignaller {
799            pid: self.process_id(),
800            handle: Child::as_raw_handle(self)
801                .as_ref()
802                .and_then(|h| filedescriptor::OwnedHandle::dup(&RawDup(*h)).ok()),
803        })
804    }
805
806    #[cfg(unix)]
807    fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
808        Box::new(ProcessSignaller {
809            pid: self.process_id(),
810        })
811    }
812}
813
814impl ChildKiller for ContainedPtyChild {
815    fn kill(&mut self) -> IoResult<()> {
816        ChildKiller::kill(&mut self.child)
817    }
818
819    fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
820        ChildKiller::clone_killer(&self.child)
821    }
822}
823
824pub fn native_pty_system() -> Box<dyn PtySystem + Send> {
825    Box::new(NativePtySystem::default())
826}
827
828#[cfg(unix)]
829pub type NativePtySystem = unix::UnixPtySystem;
830#[cfg(windows)]
831pub type NativePtySystem = win::conpty::ConPtySystem;