Untitled
raw download clone
PYTHON
views 8
,
size 923 b
#!/usr/bin/python

import socket
import os
import signal
import random
import time

# Open a socket.
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind(("", 8080))
socket.listen(128)

# For keeping track of child process pids.
N = 10
pids = []

for _ in range(N):
   pid = os.fork()
   if pid:
      pids.append(pid)
   else:
      while True:
         connection, address = socket.accept()
         print(connection.recv(1024).decode())
         message = "HTTP/1.1 200 OK\n\n <H1>Hello world</H1>\r\n\r\n"
         connection.sendall(message.encode())
         time.sleep(random.randint(1,5))
         connection.close()

# Forward any relevant signals to the child processes.
def handler(signum, frame):
   for pid in pids:
      os.kill(pid, signum)

signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGTERM, handler)

for _ in range(N):
   os.wait()
close fullscreen
Login or Register to edit or fork this paste. It's free.