I have one asynchronous worker function that collects user input from stdin
and sends it to other parts of the application. On shut down of the application, I would like to cancel my call to std::io::stdin().read_line(&mut user_input)
and return from this function.
I can not get this behavior to work. One of my attempts looks like this:
#[tokio::test]
async fn test() -> anyhow::Result<()> {
let maybe_input_handle = tokio::task::spawn_blocking(|| {
let mut user_input = String::new();
match std::io::stdin().read_line(&mut user_input) {
Ok(_) => Ok(user_input),
Err(e) => Err(e),
}
});
tokio::time::sleep(Duration::from_secs(1)).await;
maybe_input_handle.abort(); // I would like the spawned task to be cancelled immediately
let res = maybe_input_handle.await;
println!("Result is: {:#?}", res);
Ok(())
}
When calling .abort()
I would like the future of maybe_input_handle
to resolve immediately, but instead on execution I have to press a button first, so that read_line
can be resolved.
Is there a way to achieve my goal?
I considered to programmatically write to stdin
in order to cancel the thread, but I could only find out how to write to the standard input of child processes.