Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a convenience method .pid() for WaitStatus. #722

Merged
merged 1 commit into from
Aug 8, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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