Skip to content

Commit

Permalink
Add a convenience method .pid() to WaitStatus.
Browse files Browse the repository at this point in the history
  • Loading branch information
marmistrz committed Aug 8, 2017
1 parent 607ab97 commit 0370de6
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
19 changes: 19 additions & 0 deletions src/sys/wait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Pid> {
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 {
Expand Down
15 changes: 14 additions & 1 deletion test/sys/test_wait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"))]
Expand All @@ -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() -> ! {
Expand Down

0 comments on commit 0370de6

Please sign in to comment.