Skip to content

Instantly share code, notes, and snippets.

@ryochack
Last active August 19, 2018 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryochack/ab1f69d41f648e27497588693ca38275 to your computer and use it in GitHub Desktop.
Save ryochack/ab1f69d41f648e27497588693ca38275 to your computer and use it in GitHub Desktop.
extern crate nix;
use std::io;
use std::io::BufRead;
/// switch stdin to key input
fn ttyin() -> io::Result<()> {
use std::fs::File;
use nix::unistd;
use std::os::unix::io::AsRawFd;
let file = File::open("/dev/tty")?;
let _ = unistd::dup2(file.as_raw_fd(), io::stdin().as_raw_fd());
Ok(())
}
fn main() -> io::Result<()> {
let inp = io::stdin();
let mut inp = inp.lock();
let mut s = String::new();
// print out from stdin(tty or pipe)
let _ = inp.read_line(&mut s);
println!("stdin:[{}]", s);
s.clear();
ttyin()?;
// print out from stdin(tty)
let _ = inp.read_line(&mut s);
println!("stdin:[{}]", s);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment