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
extern crate nix;

use std::fs::File;
use std::io;
use std::path::Path;

use nix::unistd::dup2;
use nix::fcntl::{fcntl, FcntlArg};
use std::os::unix::io::AsRawFd;

fn ensure_stdin_open_or<P: AsRef<Path>>(path: P) -> io::Result<()> {
    let stdin_fd = 0;

    let stdin_status = fcntl(stdin_fd, FcntlArg::F_GETFD)?;

    if stdin_status == 0 {
        let file = File::open(path)?;
        let fd = file.as_raw_fd();

        dup2(fd, stdin_fd)?;
    }

    Ok(())
}

pub fn ensure() -> io::Result<()> {
    ensure_stdin_open_or("/dev/tty")
}