Skip to content

About Stdin.read() is blocked. #9

@biluohc

Description

@biluohc

ripgrep: stdin_is_readable()

// same-file= "*"
extern crate same_file;

use std::io::*;

fn main() {
    if stdin_is_readable() {
        let mut bytes = Vec::new();
        let mut s = BufReader::new(stdin());
        let mut tmp = [0u8];
        while let Ok(n) = s.read(&mut tmp) {
            if n == 0 {
                break;
            }
            bytes.push(tmp[0]);
        }
        println!("{}", String::from_utf8_lossy(&bytes[..]));
    }
}

#[cfg(unix)]
fn stdin_is_readable() -> bool {
    use same_file::Handle;
    use std::os::unix::fs::FileTypeExt;

    let ft = match Handle::stdin().and_then(|h| h.as_file().metadata()) {
        Err(_) => return false,
        Ok(md) => md.file_type(),
    };
    ft.is_file() || ft.is_fifo()
}

/// Returns true if and only if stdin is deemed searchable.
#[cfg(windows)]
fn stdin_is_readable() -> bool {
    // On Windows, it's not clear what the possibilities are to me, so just
    // always return true.
    true
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions