Skip to content

Commit

Permalink
Unblock the accept thread on shutdown
Browse files Browse the repository at this point in the history
Merge #120 a=@moises-silva r=@frewsxcv
________________________________________________________________________

I'd like to find a better way, but, this works and is not completely awful, is it? :)

If this is not acceptable I'd like to initiate a discussion on ideas on how to handle shutdown correctly. Currently if tiny-http is used in a loadable module (I am using it inside a project that can load/unload modules from an interactive command line a system administrator controls), when the server goes out of scope the socket lingers because the thread never terminates unless there's a new tcp connection received (accept is a blocking call).

An alternative to this would be to put the socket in non-blocking mode and then somehow poll() or select() on it with a timeout to check every sec for the shutdown flag (close trigger bool).

I may be wrong, but I don't see many downsides to this implementation. The Drop() call *could* hang for a bit on unusual situations like the server being inaccessible to itself (e.g 127 -> 127 firewall blocking or whatever), but the connection will timeout and move on. Most cases are better off with this as far as I can tell.

Thoughts?
  • Loading branch information
aelita-mergebot committed Aug 21, 2016
2 parents 6cba5c4 + cde7981 commit 382565f
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/lib.rs
Expand Up @@ -126,7 +126,7 @@ use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::thread;
use std::net;
use std::net::ToSocketAddrs;
use std::net::{ToSocketAddrs, TcpStream, Shutdown};
use std::time::Duration;
use std::sync::atomic::Ordering::Relaxed;

Expand Down Expand Up @@ -300,7 +300,6 @@ impl Server {
let new_client = match server.accept() {
Ok((sock, _)) => {
use util::RefinedTcpStream;

let (read_closable, write_closable) = match ssl {
None => {
RefinedTcpStream::new(sock)
Expand Down Expand Up @@ -413,5 +412,10 @@ impl<'a> Iterator for IncomingRequests<'a> {
impl Drop for Server {
fn drop(&mut self) {
self.close.store(true, Relaxed);
// Connect briefly to ourselves to unblock the accept thread
let maybe_stream = TcpStream::connect(self.listening_addr);
if let Ok(stream) = maybe_stream {
let _ = stream.shutdown(Shutdown::Both);
}
}
}

0 comments on commit 382565f

Please sign in to comment.