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

Added basic windows support #46

Closed
wants to merge 4 commits into from
Closed
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
18 changes: 16 additions & 2 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,29 @@ jobs:
run: make test

build-stable:
name: Test on 1.42.0
name: Test on 1.56.0
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v1
- uses: actions-rs/toolchain@v1
with:
toolchain: 1.42.0
toolchain: 1.56.0
profile: minimal
override: true
- name: Test
run: make test

build-latest-windows:
name: Test on Latest Windows
runs-on: windows-latest

steps:
- uses: actions/checkout@v1
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Test
run: make test
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ keywords = ["proc", "spawn", "subprocess"]
readme = "README.md"
autoexamples = true
autotests = true
rust-version = "1.42.0"
rust-version = "1.56.0"

[package.metadata.docs.rs]
all-features = true
Expand All @@ -31,6 +31,9 @@ ctor = { version = "0.1.20", optional = true }
serde_json = { version = "1.0.47", optional = true }
findshlibs = { version = "0.10.2", optional = true }

[target."cfg(windows)".dependencies]
winapi = { version = "0.3.9", features = ["errhandlingapi", "processthreadsapi"] }

[[example]]
name = "panic"
required-features = ["backtrace"]
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
[![Build Status](https://github.com/mitsuhiko/procspawn/workflows/Tests/badge.svg?branch=master)](https://github.com/mitsuhiko/procspawn/actions?query=workflow%3ATests)
[![Crates.io](https://img.shields.io/crates/d/procspawn.svg)](https://crates.io/crates/procspawn)
[![Documentation](https://docs.rs/procspawn/badge.svg)](https://docs.rs/procspawn)
[![rustc 1.42.0](https://img.shields.io/badge/rust-1.42%2B-orange.svg)](https://img.shields.io/badge/rust-1.42%2B-orange.svg)
[![rustc 1.56.0](https://img.shields.io/badge/rust-1.56%2B-orange.svg)](https://img.shields.io/badge/rust-1.42%2B-orange.svg)

This crate provides the ability to spawn processes with a function similar
to `thread::spawn`. Instead of closures it passes [`serde`](https://serde.rs/)
Expand Down
10 changes: 9 additions & 1 deletion examples/timeout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,13 @@ fn main() {
thread::sleep(Duration::from_secs(10));
});

println!("result: {:?}", handle.join_timeout(Duration::from_secs(1)));
#[cfg(unix)]
{
println!("result: {:?}", handle.join_timeout(Duration::from_secs(1)));
}
#[cfg(windows)]
{
eprintln!("Warning: windows does not yet support timeouts");
println!("result: {:?}", handle.join());
}
}
2 changes: 2 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ enum SpawnErrorKind {
Panic(PanicInfo),
IpcChannelClosed(io::Error),
Cancelled,
#[allow(unused)]
TimedOut,
}

Expand Down Expand Up @@ -173,6 +174,7 @@ impl SpawnError {
}
}

#[cfg(unix)]
pub(crate) fn new_timeout() -> SpawnError {
SpawnError {
kind: SpawnErrorKind::TimedOut,
Expand Down
7 changes: 5 additions & 2 deletions src/pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use std::process;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{mpsc, Arc, Condvar, Mutex};
use std::thread;

#[cfg(unix)]
use std::time::Duration;

use ipc_channel::ipc;
Expand Down Expand Up @@ -58,6 +60,7 @@ impl<T: Serialize + DeserializeOwned> PooledHandle<T> {
}
}

#[cfg(unix)]
pub fn join_timeout(&mut self, timeout: Duration) -> Result<T, SpawnError> {
match self.waiter_rx.recv_timeout(timeout) {
Ok(Ok(rv)) => Ok(rv),
Expand Down Expand Up @@ -415,8 +418,8 @@ fn spawn_worker(
// indicate an error.
if let Some(join_handle) = join_handle.lock().unwrap().take() {
match join_handle.join() {
Ok(()) => f(SpawnError::from(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
Ok(()) => f(SpawnError::from(io::Error::new(
io::ErrorKind::BrokenPipe,
"client process died",
))),
Err(err) => f(err),
Expand Down
32 changes: 26 additions & 6 deletions src/proc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,14 @@ use std::path::PathBuf;
use std::process::Stdio;
use std::process::{ChildStderr, ChildStdin, ChildStdout};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use std::sync::Arc;
use std::{env, mem, process};
use std::{io, thread};

#[cfg(unix)]
use std::{
io, thread,
time::{Duration, Instant},
};

use ipc_channel::ipc::{self, IpcOneShotServer, IpcReceiver, IpcSender};
use serde::{de::DeserializeOwned, Serialize};
Expand All @@ -18,6 +22,7 @@ use crate::error::{PanicInfo, SpawnError};
use crate::pool::PooledHandle;
use crate::serde::with_ipc_mode;

#[cfg(unix)]
type PreExecFunc = dyn FnMut() -> io::Result<()> + Send + Sync + 'static;

#[derive(Clone)]
Expand All @@ -28,7 +33,7 @@ pub struct ProcCommon {
#[cfg(unix)]
pub gid: Option<u32>,
#[cfg(unix)]
pub pre_exec: Option<Arc<Mutex<Box<PreExecFunc>>>>,
pub pre_exec: Option<Arc<std::sync::Mutex<Box<PreExecFunc>>>>,
}

impl fmt::Debug for ProcCommon {
Expand Down Expand Up @@ -152,7 +157,7 @@ macro_rules! define_common_methods {
where
F: FnMut() -> io::Result<()> + Send + Sync + 'static,
{
self.common.pre_exec = Some(Arc::new(Mutex::new(Box::new(f))));
self.common.pre_exec = Some(Arc::new(std::sync::Mutex::new(Box::new(f))));
self
}
};
Expand Down Expand Up @@ -331,7 +336,19 @@ impl ProcessHandleState {
self.exited.store(true, Ordering::SeqCst);
if let Some(pid) = self.pid() {
unsafe {
libc::kill(pid as i32, libc::SIGKILL);
#[cfg(unix)]
{
libc::kill(pid as i32, libc::SIGKILL);
}
#[cfg(windows)]
{
let proc = winapi::um::processthreadsapi::OpenProcess(
winapi::um::winnt::PROCESS_ALL_ACCESS,
0,
pid as _,
);
winapi::um::processthreadsapi::TerminateProcess(proc, 1);
}
}
}
}
Expand All @@ -344,6 +361,7 @@ pub struct ProcessHandle<T> {
pub(crate) state: Arc<ProcessHandleState>,
}

#[cfg(unix)]
fn is_ipc_timeout(err: &ipc_channel::ipc::TryRecvError) -> bool {
matches!(err, ipc_channel::ipc::TryRecvError::Empty)
}
Expand Down Expand Up @@ -388,6 +406,7 @@ impl<T: Serialize + DeserializeOwned> ProcessHandle<T> {
rv
}

#[cfg(unix)]
pub fn join_timeout(&mut self, timeout: Duration) -> Result<T, SpawnError> {
let deadline = match Instant::now().checked_add(timeout) {
Some(deadline) => deadline,
Expand Down Expand Up @@ -511,6 +530,7 @@ impl<T: Serialize + DeserializeOwned> JoinHandle<T> {
}

/// Like `join` but with a timeout.
#[cfg(unix)]
pub fn join_timeout(self, timeout: Duration) -> Result<T, SpawnError> {
match self.inner {
Ok(JoinHandleInner::Process(mut handle)) => handle.join_timeout(timeout),
Expand Down
1 change: 1 addition & 0 deletions tests/test_basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ fn test_nested() {
}

#[test]
#[cfg(unix)]
fn test_timeout() {
let handle = spawn((), |()| {
thread::sleep(Duration::from_secs(10));
Expand Down
3 changes: 2 additions & 1 deletion tests/test_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ fn test_basic() {
let mut ok = 0;
let mut failed = 0;
for handle in handles {
if handle.join_timeout(Duration::from_secs(5)).is_ok() {
if handle.join().is_ok() {
ok += 1;
} else {
failed += 1;
Expand Down Expand Up @@ -59,6 +59,7 @@ fn test_overload() {
}

#[test]
#[cfg(unix)]
fn test_timeout() {
let pool = Pool::new(2).unwrap();

Expand Down