summaryrefslogtreecommitdiffstats
path: root/vendor/wait-timeout/src/windows.rs
blob: a3aa10468fcb015a88254435189913ee414faefe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
use std::io;
use std::os::windows::prelude::*;
use std::process::{Child, ExitStatus};
use std::time::Duration;

type DWORD = u32;
type HANDLE = *mut u8;

const WAIT_OBJECT_0: DWORD = 0x00000000;
const WAIT_TIMEOUT: DWORD = 258;

extern "system" {
    fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD;
}

pub fn wait_timeout(child: &mut Child, dur: Duration)
                       -> io::Result<Option<ExitStatus>> {
    let ms = dur.as_secs().checked_mul(1000).and_then(|amt| {
        amt.checked_add((dur.subsec_nanos() / 1_000_000) as u64)
    }).expect("failed to convert duration to milliseconds");
    let ms = if ms > (DWORD::max_value() as u64) {
        DWORD::max_value()
    } else {
        ms as DWORD
    };
    unsafe {
        match WaitForSingleObject(child.as_raw_handle() as *mut _, ms) {
            WAIT_OBJECT_0 => {}
            WAIT_TIMEOUT => return Ok(None),
            _ => return Err(io::Error::last_os_error()),
        }
    }
    child.try_wait()
}