Last active
March 15, 2020 12:09
-
-
Save pedrominicz/3f8db05194ae93288d0af42f71709069 to your computer and use it in GitHub Desktop.
Inter-process communication using datagram sockets (i.e. UDP).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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_DGRAM` is | |
# a datagram-based protocol (i.e. UDP). Note that the parent process and the | |
# child process each create their own socket. | |
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
# `gethostname` returns the current host name. | |
address = (socket.gethostname(), 5000) | |
if pid == 0: | |
# The child process encodes the user input into `<class 'bytes'>` and sends | |
# it to `address`. | |
udp.sendto(input().encode(), address) | |
else: | |
# The parent process binds `address` so it can receive data sent to it. | |
udp.bind(address) | |
# Receive data from the socket. Note that `socket.socket.recv` by default | |
# blocks, so the parent waits until the user has finished entering the | |
# input. | |
print(udp.recv(4096).decode()) | |
udp.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment