Python - how to relaunch the application on the fly while the application having a TCP port in listening mode?
linux, network-programming, python, python-2.7
Solution
You will have to find the Python equivalent of setting `SO_REUSEADDR` on the socket before you bind it. Ensuring the socket is closed on exit as recommended in other answers is neither necessary nor sufficient, as (a) sockets get closed by the OS when the process exits, and (b) you still have to overcome accepted connections in the `TIME_WAIT` state, which only `SO_REUSEADDR` can do.
Problem
What is the best way to relaunch the application where it was running a listening TCP port? Problem is: if i quickly launch the application as relaunch it fails because the socket which was listening is already in use. How to safely relaunch in such case? ``` socket.error: [Errno 98] Address already in use ``` Code: ``` #!/usr/bin/python import sys,os import pygtk, gtk, gobject import socket, datetime, threading import ConfigParser import urllib2 import subprocess def server(host, port): sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((host, port)) sock.listen(1) print "Listening... " gobject.io_add_watch(sock, gobject.IO_IN, listener) def listener(sock, *args): conn, addr = sock.accept() print "Connected" gobject.io_add_watch(conn, gobject.IO_IN, handler) return True def handler(conn, *args): line = conn.recv(4096) if not len(line): print "Connection closed." return False else: print line if line.startswith("unittest"): subprocess.call("/var/tmp/runme.sh", shell=True) else: print "not ok" return True server('localhost', 8080) gobject.MainLoop().run() ``` runme.sh ``` #!/bin/bash ps aux | grep py.py | awk '{print $2}' | xargs kill -9; export DISPLAY=:0.0 && lsof -i tcp:58888 | grep LISTEN | awk '{print $2}' | xargs kill -9; export DISPLAY=:0.0 && java -cp Something.jar System.V & export DISPLAY=:0.0 && /var/tmp/py.py & ``` EDIT: Note that, i am using Java and Python together as one application with two layer. So runme.sh is my startup script to launch both apps at same time. From Java i press the Python relaunch button. But Python does not relaunch because the kill is done via BASH.