Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I read from stdin in a non-canonical way?

Tags:

linux

rust

Is there any way one could read from stdin in non-canonical mode under Linux? Non-canonical input means that calls to read() on stdin shall return as soon as the user types, which is not the default behaviour, as one can see by trying:

// Create a buffer
let mut buffer :[u8; 1] = [0];
// Loops over the input from stdin, one character a time
while io::stdin().read(&mut buffer).unwrap() > 0 {
    println!("{:?}", buffer);
}

This code waits for the user to press return to print the contents of buffer. The desired behaviour would be for it to print as the user typed. In the documentation for Stdin (the struct returned by the stdin() call in the code above), there is no reference to how one could change this default behaviour.

like image 501
Felipe Tavares Avatar asked Nov 09 '22 01:11

Felipe Tavares


1 Answers

No, not without external crates or unsafe FFI code. You will probably want to use the termios functions. Specifically, see ICANON and tcsetattr. The crate nix has bindings for these functions. See here for an example of how to use them in Rust.

like image 168
Adrian Avatar answered Nov 15 '22 07:11

Adrian