How to exit blocking TcpListener :: accept call?

I run the accept function of the TCP listener in a loop in a separate thread. I would like to disable this topic gracefully, but I do not see any shutdown mechanism that I could use to refuse acceptance.

My current approach looks something like this:

 use std::net::TcpListener; use std::thread::spawn; fn main() { let tcp_listener = TcpListener::bind((("0.0.0.0"), 0)).unwrap(); let tcp_listener2 = tcp_listener.try_clone().unwrap(); let t = spawn(move || { loop { match tcp_listener2.accept() { Ok(_) => { } Err(_) => { break; } } } }); drop(tcp_listener); assert!(t.join().is_ok()); } 

But this does not do the trick (perhaps because I am only throwing a cloned copy?). Any thought on how to properly disable such a stream?

(for reference, I also asked this question in the rust user forum )

+6
source share
1 answer

The question is fundamental, since at the end the call to accept() converted to libc::accept() (see here and here ).

The solution would be to use nonblocking-io, e.g. mio .


Edi: After some consideration, I explored the possibility of interrupting accept() with close() . It seems unreliable. But this is : Using shutdown() . TcpStream exposes this function, but it seems to be the only case. Could be a flaw in the API?

+5
source

Source: https://habr.com/ru/post/984901/


All Articles