Skip to content

Instantly share code, notes, and snippets.

@satchamo
Created December 31, 2020 17:58
Show Gist options
  • Save satchamo/56886677e70febc841f7c93061e37b09 to your computer and use it in GitHub Desktop.
Save satchamo/56886677e70febc841f7c93061e37b09 to your computer and use it in GitHub Desktop.
import asyncio
import functools
import os
import signal
import socket
import websockets
from multiprocessing import Process
from pathlib import Path
# this is set by the parent, and inherited by the children
sock = None
async def handler(*args, **kwargs):
while True:
print("being handled")
await asyncio.sleep(1)
async def setup():
event = asyncio.Event()
server = websockets.unix_serve(
handler,
# this path argument is REQUIRED by websockets to branch to create_unix_server
# but we don't actually want to specify a path, because we're passing in the `sock` instead.
# Python blocks us from specifying both:
# https://github.com/python/cpython/blob/66d3b589c44fcbcf9afe1e442d9beac3bd8bcd34/Lib/asyncio/unix_events.py#L245
path="thisisnotused",
sock=sock,
close_timeout=.2,
max_size=2**16,
compression=None,
backlog=65535)
# hack to strip the `path` argument (uncomment to make it work)
# partial = server._create_server
# server._create_server = functools.partial(partial.func, *partial.args[:-1], **partial.keywords)
async with server:
print("Started server")
await event.wait()
print("Exiting")
def child():
asyncio.get_event_loop().run_until_complete(setup())
if __name__ == "__main__":
# create the socket in the parent
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
socket_path = Path(__file__).parent / "ws_server.sock"
try:
os.unlink(socket_path)
except FileNotFoundError:
pass
sock.bind(str(socket_path))
sock.listen(65535)
sock.setblocking(False)
# just so we don't have any errors during debugging
os.chmod(str(socket_path), 0o777)
workers = []
# these child processes will inherit the listening socket
# on unix because of the fork() system call
for i in range(2):
p = Process(target=child)
p.start()
workers.append(p)
for p in workers:
p.join()
print("Parent exiting")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment