From 0370de6cb99a320b67afebe048e9b1d9a7474b13 Mon Sep 17 00:00:00 2001 From: Marcin Mielniczuk Date: Mon, 7 Aug 2017 15:10:41 +0200 Subject: [PATCH] Add a convenience method .pid() to WaitStatus. --- CHANGELOG.md | 2 ++ src/sys/wait.rs | 19 +++++++++++++++++++ test/sys/test_wait.rs | 15 ++++++++++++++- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f1d278d677..247e9b367b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,8 @@ This project adheres to [Semantic Versioning](http://semver.org/). ([#672](https://github.com/nix-rust/nix/pull/672)) - Added protocol families in `AddressFamily` enum. ([#647](https://github.com/nix-rust/nix/pull/647)) +- Added the `pid()` method to `WaitStatus` for extracting the PID. + ([#722](https://github.com/nix-rust/nix/pull/722)) ### Changed - Renamed existing `ptrace` wrappers to encourage namespacing ([#692](https://github.com/nix-rust/nix/pull/692)) diff --git a/src/sys/wait.rs b/src/sys/wait.rs index f31f666d6d..b2ca3bd653 100644 --- a/src/sys/wait.rs +++ b/src/sys/wait.rs @@ -93,6 +93,25 @@ pub enum WaitStatus { StillAlive } +impl WaitStatus { + /// Extracts the PID from the WaitStatus unless it equals StillAlive. + pub fn pid(&self) -> Option { + use self::WaitStatus::*; + match *self { + Exited(p, _) => Some(p), + Signaled(p, _, _) => Some(p), + Stopped(p, _) => Some(p), + Continued(p) => Some(p), + StillAlive => None, + + #[cfg(any(target_os = "linux", target_os = "android"))] + PtraceEvent(p, _, _) => Some(p), + #[cfg(any(target_os = "linux", target_os = "android"))] + PtraceSyscall(p) => Some(p), + } + } +} + #[cfg(any(target_os = "linux", target_os = "android"))] mod status { diff --git a/test/sys/test_wait.rs b/test/sys/test_wait.rs index 8d2ca85fda..620a4e330b 100644 --- a/test/sys/test_wait.rs +++ b/test/sys/test_wait.rs @@ -37,6 +37,19 @@ fn test_wait_exit() { } } +#[test] +fn test_waitstatus_pid() { + let _m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test"); + + match fork().unwrap() { + Child => unsafe { _exit(0) }, + Parent { child } => { + let status = waitpid(child, None).unwrap(); + assert_eq!(status.pid(), Some(child)); + } + } +} + #[cfg(any(target_os = "linux", target_os = "android"))] // FIXME: qemu-user doesn't implement ptrace on most arches #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] @@ -47,7 +60,7 @@ mod ptrace { use nix::sys::wait::*; use nix::unistd::*; use nix::unistd::ForkResult::*; - use std::{ptr, process}; + use std::ptr; use libc::_exit; fn ptrace_child() -> ! {