title: How to close socket connection on Ctrl-C in a python programme
body: <pre><code>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.bind((HOST, PORT))
  s.listen(1)
  
  any_connection = False
  
  while True:
      try:
          conn, addr = s.accept()
          data = conn.recv(1024)
          any_connection = True
  
          # keep looking
          if not data: continue
  
          pid = os.fork()
  
          if pid == 0:
              server_process(data, conn)
      except KeyboardInterrupt:
          break
  
  if any_connection:
      print("Closing connection")
      conn.close()
  </code></pre>
  
  <p>I'm catching the <code>KeyboardInterrupt</code>signal here on an infinite-running TCP server I wrote in Python. However, even though I know it is closing the connection because it prints <code>Closing Connection</code>, when I try to re-run the server I get:</p>
  
  <p><code>OSError: [Errno 48] Address already in use</code></p>
  
  <p>I have no idea what's happening because I know for sure I'm calling <code>conn.close()</code>.</p>
  
  <p>And running <code>killall python3</code>doesn't fix it, I keep getting the error unless I wait for a long time or change port. Also I tried to grep all <code>python3</code> processes but I get nothing.</p>
  
  <p>I'm running OS X Yosemite.</p>