Hey. There is a flask that communicates with the browser via http. For some reason, sometimes, after running Ctrl + C, it turns out that I still have a hanging connection, but no process is associated with it. Therefore, I can not reconnect to the browser, as this port and address are busy. How to kill a connection under Ubuntu 16.04?

This is what netstat produces:

$ netstat -na | grep :8080 tcp 0 0 127.0.0.1:8080 0.0.0.0:* LISTEN 

Here is an example of the server code:

 from flask import Flask, request import json import requests app = Flask(__name__) @app.route('/search/3', methods=['GET', 'POST']) def GetFromBrowser(): if request.method == 'GET': try: connection = requests.get("http://localhost:8082/search/3", params = request.args) except: print("python: Unexpected connection") return "" # ... return connection.text else: return "" if __name__ == '__main__': app.run(host = '127.0.0.1', port = '8080') 

    2 answers 2

    Most likely the case is in the lines:

     try: connection = requests.get("http://localhost:8082/search/3", params = request.args) except: print("python: Unexpected connection") return "" 

    When you press Ctrl+C at requests.get() , a KeyboardInterrupt error is raised and processed by your except . Thus, the script does not fall.

    Try to test the script with the command ps -ef | grep python ps -ef | grep python .

    Often in programs you can see this processing KeyboardInterrupt :

     import time try: time.sleep(100) # ΠŸΡ€ΠΎΡΡ‚ΠΎ для ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π° except KeyboardInterrupt: print('Π—Π΄Π΅ΡΡŒ Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎ ΠΊΠ°ΠΊΠΎΠ΅-Π½ΠΈΠ±ΡƒΠ΄ΡŒ Π»ΠΎΠ³ΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠ΅ ΠΈΠ»ΠΈ сообщСниС Π² консоль') exit(0) 
    • Is it better to handle this exception separately? - hedgehogues
    • @hedgehogues supplemented the answer - faoxis

    Hey. And you try to find a process that remains to hang, then you can understand what the problem is.

    1. lsof -i tcp:8080 or netstat -nap | grep :443 netstat -nap | grep :443
    2. you can try to work out why the connection is not chopped off in the process logs, but you can just kill the process - kill -s KILL <pid ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ Π²Ρ‹Π²Π΅Π΄Π΅Ρ‚ lsof>