Skip to content

Instantly share code, notes, and snippets.

@pedrominicz
Created March 15, 2020 14:08
Show Gist options
  • Save pedrominicz/c26d8f8efc7148f387c467197f8c98a2 to your computer and use it in GitHub Desktop.
Save pedrominicz/c26d8f8efc7148f387c467197f8c98a2 to your computer and use it in GitHub Desktop.
Server mediated inter-process communication.
import itertools
import os
import socket
import threading
import time
# This program illustrates a simple TCP server used to mediate inter-process
# communication. Three processes are created: a server, a producer, and a
# consumer. The server creates a thread to handle each incoming connection.
address = (socket.gethostname(), 5000)
if os.fork() != 0:
# Create a TCP socket for the _actual_ server.
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(address)
server.listen(2)
connections = []
# Each connection will execute this function on a separate thread.
def thread(connection):
while True:
# `socket.socket.recv` blocks. This is not a proble, however,
# because the loop below is able to send messages even if the
# thread that owns another connection is currently blocked waiting
# a message.
message = connection.recv(4096)
for connection in connections:
connection.send(message)
while True:
connection, address = server.accept()
connections.append(connection)
# Note the argument `args` requires a tuple and that `(connection, )`
# is parsed as a tuple while `(connection)` is equivalent to
# `connection` but with superfluous parenthesis.
threading.Thread(target=thread, args=(connection, )).start()
else:
if os.fork() == 0:
# Create a TCP socket for the producer.
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.connect(address)
# `itertools.count` returns an iterator that counts from zero to
# infinity.
for i in itertools.count():
server.send(str(i).encode())
time.sleep(1)
else:
# Create a TCP socket for the consumer.
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.connect(address)
while True:
print(server.recv(4096).decode())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment