karlseguin / http.zig

An HTTP/1.1 server for zig
MIT License
533 stars 41 forks source link

Implement stop function. #23

Closed monomycelium closed 10 months ago

monomycelium commented 1 year ago

Hello, there! This seems like a great server implementation. However, would a function to stop the server be feasible? For example, if the SIGINT signal is passed to a program that is listening to the server, we could handle the signal and gracefully shut the server down (e.g. closing resources). We could possibly have a global boolean and pass the reference to the Server initialisers. The signal handler would set the boolean to false to stop the server loop and clean up resources. Do you think it would be practical?

karlseguin commented 1 year ago

I've thought of it, but I'm not sure how to implement this cleanly. The server is blocked on a call to accept.

while (true) {
  if (socket.accept()) |conn| {
    // handle conn
  }
}

It's possible to check a thread-safe boolean inside the while loop, but there's no great way to unblock accept. Calling close on the socket for another thread unblocks accept on BSD, but not Linux from what I can tell.

I think you'd have to use select or poll to timeout the accept, but then you get into cross platform issues..not to mention that isn't a great API. You'd have to wait up to TIMEOUT before it actually shuts down. Plus, something annoying about having this overhead in the main loop.

TL;DR - I don't know how to do it.

karlseguin commented 10 months ago

With the recent changes this is now supported on the master branch.

const thread = try server.listenInNewThread()
...
server.stop()
thread.join();