Multithreaded webserver in Python
<p>An example from a video lecture. Background: the lecturer gave a simplest web server in python. He created a socket, binded it, made listening, accepted a connection, received data, and send it back to the client in uppercase. Then he said that there is a drawback: this web server is single-threaded. Then let's fork.</p>

<p>I can't understand the example well enough. But to start with, the program exits (sys.exit()). But I can't run it again: </p>

<p><strong>socket.error: [Errno 98] Address already in use.</strong></p>

<p>I try to find out which process is listening on port 8080: netstat --listen | grep 8080. Nothing.</p>

<p><strong>Well, what is listening on 8080? And how to kill it?</strong></p>

<p><strong>Added later:</strong>
There is a feeling that if I wait for some time (say, 5-10 minutes), I can run the program again.</p>

<pre><code>import os
import socket
import sys


server_socket = socket.socket()
server_socket.bind(('', 8080))
server_socket.listen(10)
print "Listening"


while True:
    client_socket, remote_address = server_socket.accept()
    print "PID: {}".format(os.getpid())
    child_pid = os.fork()
    print "child_pid {}".format(child_pid)

    if child_pid == 0:    
        request = client_socket.recv(1024)
        client_socket.send(request.upper())
        print '(child {}): {}'.format(client_socket.getpeername(), request)
        client_socket.close()
        sys.exit()
    else:
        client_socket.close()

server_socket.close()
</code></pre>