8 releases

Uses old Rust 2015

0.4.0 Oct 25, 2024
0.3.3 Jan 11, 2023
0.3.2 Jul 19, 2022
0.3.1 Mar 3, 2020
0.1.0 Sep 6, 2017

#55 in Unix APIs

Download history 1655/week @ 2024-07-18 1518/week @ 2024-07-25 1546/week @ 2024-08-01 1678/week @ 2024-08-08 1802/week @ 2024-08-15 2217/week @ 2024-08-22 1673/week @ 2024-08-29 2284/week @ 2024-09-05 2240/week @ 2024-09-12 1817/week @ 2024-09-19 2543/week @ 2024-09-26 3291/week @ 2024-10-03 2933/week @ 2024-10-10 3257/week @ 2024-10-17 3080/week @ 2024-10-24 2656/week @ 2024-10-31

12,626 downloads per month
Used in 9 crates (8 directly)

MIT/Apache

20KB
265 lines

timeout-readwrite

A Rust crate providing Reader and Writer structs that timeout.

Build Status

Why is this useful when we have async I/O? Take, for instance, the case where you are interacting with a subprocess in the background. This subprocess is waiting for some event to occur and, when it does, will output a message to standard out. Your program is waiting for input to come in over the subprocesses standard out stream. Perhaps you want to write code like the following that does something interesting for each line as it comes in, but you do not mind blocking until the next line comes in:

use std::io::{BufRead, BufReader};
use std::io::Result;
use std::process;

fn each_line<R: BufRead>(rdr: R) -> Result<()> {
    let lines = rdr.lines();

    for rslt_line in lines {
        let line = rslt_line?;
        println!("{}", line);
    }
    Ok(())
}

fn do_command(cmd: &str) -> Result<()> {
    let mut cmd = process::Command::new(cmd);
    let child = cmd.stdout(process::Stdio::piped())
        .stderr(process::Stdio::null())
        .spawn().expect("spawning did not succeed");

    let stdout = child.stdout?;
    each_line(BufReader::new(stdout))
}

This works as long as the spawned process does not hang and provides output at a reasonable rate. If the spawned process hangs, though, your program will be blocked forever waiting for another line to appear. Ideally, we would like to be able to timeout the read operation and return an error in that case. Hence, a TimeoutReader struct to provide that ability. With that, we can change our do_command function like so:

use std::time::Duration;

fn do_command(cmd: &str) -> Result<()> {
    let mut cmd = process::Command::new(cmd);
    let child = cmd.stdout(process::Stdio::piped())
        .stderr(process::Stdio::null())
        .spawn().expect("spawning did not succeed");

    let stdout = child.stdout?;
    each_line(BufReader::new(TimeoutReader::new(stdout, Duration::new(5, 0))))
}

Now, if the program ever has to wait longer than 5 seconds without receiving data from the subprocess, the read call behind the Lines iterator will fail with an ErrorKind::TimeOut.

Documentation

Module documentation with examples

Usage

Add this to your Cargo.toml:

[dependencies]
timeout-readwrite = "0.3.1"

and this to your crate root:

extern crate timeout_readwrite;

Dependencies

~1.5MB
~35K SLoC