console-rs / console

A rust console and terminal abstraction
MIT License
907 stars 107 forks source link

Unblocking `read_key()` / writing to stdin #188

Open george-cosma opened 9 months ago

george-cosma commented 9 months ago

I've been recently writing some async code, and one of the requirements was reading from the consol in raw mode, in a separate thread. Now, this isn't an issue per se:

    let console_result = tokio::task::spawn_blocking(move || Term::stdout().read_key()).await?;

Using this code snippet, I can put the blocking read_key() on it's own thread and be happy. Unfortunately, if I need to cancel this operation I don't have a consistent mechanism to do so. Tokio doesn't really allow me to kill the blocking thread directly, or I don't know of a way. There isn't a pretty way to do async console reading/writing - there are some options on windows, but no idea on unix systems.

An alternative would be implementing the functionality to write to stdin. I've made a rough proof-of-conept in a local fork that sends a pre-determined key. A proper system to write to stdin would solve this issue, but does require the implementation of a new feature

Note: my implementation of writing to stdin may not be that stable, but it works for me:

Note: although TIOCSTI was revoked in OpenBSD 6.2 (Oct 2017), apparently the Linux Kernel developers are of the opposite mind, categorically refusing to revoke it (you can read more about this in the OpenBSD Journal).

[Source]

fadeevab commented 3 months ago

I faced the same problem with the same idea of the solution.