process: Refactor Unix process handling

This commit is contained in:
Ivan Petkov
2019-06-24 16:57:18 -07:00
parent 10fd2afd18
commit db0c4147c8
2 changed files with 336 additions and 97 deletions
+23 -97
View File
@@ -24,35 +24,44 @@
extern crate libc;
extern crate tokio_signal;
use std::io;
use std::os::unix::prelude::*;
use std::process::{self, ExitStatus};
mod reap;
use futures::future::FlattenStream;
use futures::{Future, Poll, Async, Stream};
use futures::{Future, Poll};
use mio::unix::{EventedFd, UnixReady};
use mio::{PollOpt, Ready, Token};
use mio::event::Evented;
use mio;
use self::reap::{EventedReaper, Kill, Wait};
use self::tokio_signal::unix::Signal;
use std::fmt;
use std::io;
use std::os::unix::io::{AsRawFd, RawFd};
use std::process::{self, ExitStatus};
use tokio_io::IoFuture;
use tokio_reactor::{Handle, PollEvented};
impl Wait for process::Child {
fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
self.try_wait()
}
}
impl Kill for process::Child {
fn kill(&mut self) -> io::Result<()> {
self.kill()
}
}
#[must_use = "futures do nothing unless polled"]
pub struct Child {
inner: process::Child,
reaped: bool,
sigchld: FlattenStream<IoFuture<Signal>>,
inner: EventedReaper<process::Child, FlattenStream<IoFuture<Signal>>>,
}
impl fmt::Debug for Child {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Child")
.field("pid", &self.inner.id())
.field("inner", &self.inner)
.field("reaped", &self.reaped)
.field("sigchld", &"..")
.finish()
}
}
@@ -65,10 +74,9 @@ impl Child {
let stdout = stdio(inner.stdout.take(), handle)?;
let stderr = stdio(inner.stderr.take(), handle)?;
let signal = Signal::with_handle(libc::SIGCHLD, handle).flatten_stream();
let child = Child {
inner: inner,
reaped: false,
sigchld: Signal::with_handle(libc::SIGCHLD, handle).flatten_stream(),
inner: EventedReaper::new(inner, signal),
};
Ok((child, stdin, stdout, stderr))
@@ -79,93 +87,11 @@ impl Child {
}
pub fn kill(&mut self) -> io::Result<()> {
if !self.reaped {
// NB: SIGKILL cannnot be caught, so the process will definitely exit immediately.
// We're not waiting for the process itself but for the kernel to execute the kill.
self.inner.kill()?;
let _ = self.try_wait(true);
}
Ok(())
self.inner.kill()
}
pub fn poll_exit(&mut self) -> Poll<ExitStatus, io::Error> {
loop {
// Ensure we don't register for additional notifications
// if the child has already finished.
if self.reaped {
return Ok(Async::NotReady);
}
// If the child hasn't exited yet, then it's our responsibility to
// ensure the current task gets notified when it might be able to
// make progress.
//
// As described in `spawn` above, we just indicate that we can
// next make progress once a SIGCHLD is received.
//
// However, we will register for a notification on the next signal
// BEFORE we poll the child. Otherwise it is possible that the child
// can exit and the signal can arrive after we last polled the child,
// but before we've registered for a notification on the next signal
// (this can cause a deadlock if there are no more spawned children
// which can generate a different signal for us). A side effect of
// pre-registering for signal notifications is that when the child
// exits, we will have already registered for an additional
// notification we don't need to consume. If another signal arrives,
// this future's task will be notified/woken up again. Since the
// futures model allows for spurious wake ups this extra wakeup
// should not cause significant issues with parent futures.
let registered_interest = try!(self.sigchld.poll()).is_not_ready();
if let Some(e) = try!(self.try_wait(false)) {
return Ok(e.into());
}
// If our attempt to poll for the next signal was not ready, then
// we've arranged for our task to get notified and we can bail out.
if registered_interest {
return Ok(Async::NotReady);
} else {
// Otherwise, if the signal stream delivered a signal to us, we
// won't get notified at the next signal, so we'll loop and try
// again.
continue;
}
}
}
fn try_wait(&mut self, block_on_wait: bool) -> io::Result<Option<ExitStatus>> {
assert!(!self.reaped);
let exit = try!(try_wait_process(self.id() as libc::pid_t, block_on_wait));
if let Some(_) = exit {
self.reaped = true;
}
Ok(exit)
}
}
fn try_wait_process(id: libc::pid_t, block_on_wait: bool) -> io::Result<Option<ExitStatus>> {
let wait_flags = if block_on_wait { 0 } else { libc::WNOHANG };
let mut status = 0;
loop {
match unsafe { libc::waitpid(id, &mut status, wait_flags) } {
0 => return Ok(None),
n if n < 0 => {
let err = io::Error::last_os_error();
if err.kind() == io::ErrorKind::Interrupted {
continue
}
return Err(err)
}
n => {
assert_eq!(n, id);
return Ok(Some(ExitStatus::from_raw(status)))
}
}
self.inner.poll()
}
}