dabeaz / curio

Good Curio!
Other
4.02k stars 241 forks source link

How to kill TCP server? #209

Closed SuperShinyEyes closed 7 years ago

SuperShinyEyes commented 7 years ago

I looked through the documentation and kernel.py but I can't find anywhere how to suspend or kill a TCP server.

dabeaz commented 7 years ago

This really depends on what you mean by "kill" or "suspend". Is this in response to a signal? What platform?

The typical way one would kill a Curio task is to cancel it. I guess the real question is what triggers that.

SuperShinyEyes commented 7 years ago

Thank you David for the reply!

Is this in response to a signal?

No. I was wondering how the socket of a TCP server gets closed as a program gets shutdown. For instance(if I understood correctly), in a user program a user doesn't need to explicitly call close() for a socket ever.

try:
    run(tcp_server, '', 11000, self.start_recv_mesh)
    # self.listen()
except KeyboardInterrupt:
    pass
finally:
    print("Bye bye")
    # This is where I would close a socket usually .
    # tcp_server.close()
    # However Curio will handle everything for you.
    # But can I still do it manually?

What platform?

  • Mac 10.12.3
  • Python 3.6.0

I spent two hours looking at Curio source code:

I found that in channel.py and io.py there are close methods in each.

# channel.py 
# line 248
async def close(self):
    if self.sock:
        await self.sock.close()
    self.sock = None
# io.py
# line 249
async def close(self):
    if self._socket:
        self._socket.close()
    self._socket = None
    self._fileno = -1

However, I couldn't find anywhere where you call those methods except an exception is raised.

So what is happening under the hood? What is happening at the time of shutdown? How are the resources being released?

Thank you David for your amazing work and taking your time to reply for a newbie question.

dabeaz commented 7 years ago

Sockets are being closed via context-managers. The tcp_server() code uses async with statements both on the server socket (for accepting connections) and on the client sockets. The __aexit__() methods in the io.c file should either be calling the synchronous __exit__() method (which will close a socket) or redirecting to the close() method.

SuperShinyEyes commented 7 years ago

Ok! Thanks a lot David for your detailed reply :)

giampaolo commented 7 years ago

Speaking of which, is there a way to stop the loop from anywhere in the app? Something like raise curio.StopLoop.