Reputation: 239
How to exit a server completely in Python? Code like server.shutdown()
just shuts down the incoming requests. Can anyone suggest any code for complete exit of server? It's a simple socketserver.
This is my code for server:
#!/usr/bin/python
import socket
from threading import Thread
class sockServer:
def __init__(self,port):
self.socket= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(port)
self.socket.listen(5)
def _run(self):
while True:
request, client_address =self.socket.accept()
counter=self.req_thread(self,request)
counter.start()
class req_thread(Thread):
def __init__(self,controller,request):
Thread.__init__(self)
self.controller=controller
self.request=request
self.setDaemon(True)
def run(self):
input=self.request.makefile('rb',0)
output=self.request.makefile('wb',0)
l=True
i=0
try:
while l:
l=input.readline()
if l!="exit\r\n":
print "x"
output.write(bytes('hello\n'))
else:
print "y"
self.request.shutdown(2)
run=False
except socket.error:
pass
if __name__ == '__main__':
import sys
if len(sys.argv) < 3:
print('Usage: %s [hostname] [port number]' % sys.argv[0])
sys.exit(1)
hostname = sys.argv[1]
port = int(sys.argv[2])
global run
run=True
while run:
server=sockServer((hostname,port))
server._run()
The method using the variable run
isn't doing any good!
Upvotes: 2
Views: 2681
Reputation: 1671
If you are just trying to exit the program completely then you can always add import sys
and then in do this:
class req_thread(Thread):
def __init__(self,controller,request):
Thread.__init__(self)
self.controller=controller
self.request=request
self.setDaemon(True)
def run(self):
input=self.request.makefile('rb',0)
output=self.request.makefile('wb',0)
l=True
i=0
try:
while l:
l=input.readline()
if l!="exit\r\n":
print "x"
output.write(bytes('hello\n'))
else:
print "y"
self.request.shutdown(2)
sys.exit(0)
run=False
except socket.error:
pass
Upvotes: 2
Reputation: 25569
If sys.exit isn't working then you can use a more extreme version which directly calls the os.
import os
os._exit()
You will have to do this if the server has forked a new process or thread. Which is what you are doing and why sys.exit isn't working as you expect. See this explanation of the difference between the two calls: What is difference between sys.exit(0) and os._exit(0)
Upvotes: 2