Skip to content

Instantly share code, notes, and snippets.

@pedrominicz
Last active March 15, 2020 12:22
Show Gist options
  • Save pedrominicz/ffe038d8588fd2b74f5bf6611bf796c4 to your computer and use it in GitHub Desktop.
Save pedrominicz/ffe038d8588fd2b74f5bf6611bf796c4 to your computer and use it in GitHub Desktop.
Inter-process communication using stream sockets (i.e. TCP).
import os
import socket
# `fork` current process. The child's PID is returned to the parent and `0` is
# returned to the child.
pid = os.fork()
# Create a socket. `AF_INET` is the address family for IPv4 and `SOCK_STREAM`
# is a connection-based protocol (i.e. TCP).
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# `gethostname` returns the current host name.
address = (socket.gethostname(), 5000)
if pid == 0:
# Connect to the parent.
tcp.connect(address)
# The child process encodes the user input into `<class 'bytes'>` and sends
# it to the parent.
tcp.send(input().encode())
else:
# The parent process binds `address` so it can receive data sent to it.
tcp.bind(address)
# Enable server to accept a maximum of one connection.
tcp.listen(1)
# Wait for an incoming connection. The return value is a tuple containing a
# socket object representing the connection and the address of the incoming
# connection.
connection, address = tcp.accept()
# Receive data from the connection. Note that `socket.socket.recv` by
# default blocks, so the parent waits until the user has finished entering
# the input.
print(connection.recv(4096).decode())
connection.close()
tcp.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment