socketify.py/examples/forks.py

33 wiersze
745 B
Python
Czysty Zwykły widok Historia

2022-05-31 21:51:39 +00:00
from socketify import App
import os
import multiprocessing
def run_app():
app = App()
app.get("/", lambda res, req: res.end("Hello, World!"))
2022-11-16 19:28:46 +00:00
app.listen(
3000,
lambda config: print(
"PID %d Listening on port http://localhost:%d now\n"
% (os.getpid(), config.port)
),
)
2022-05-31 21:51:39 +00:00
app.run()
2022-11-16 19:28:46 +00:00
2023-03-12 19:08:54 +00:00
pid_list = []
# fork limiting the cpu count - 1
for _ in range(1, multiprocessing.cpu_count()):
pid = os.fork()
2022-05-31 21:51:39 +00:00
# n greater than 0 means parent process
2023-03-12 19:08:54 +00:00
if not pid > 0:
2022-05-31 21:51:39 +00:00
run_app()
2023-03-12 19:08:54 +00:00
break
pid_list.append(pid)
2022-05-31 21:51:39 +00:00
2022-11-16 19:28:46 +00:00
run_app() # run app on the main process too :)
2023-03-12 19:08:54 +00:00
# sigint everything to gracefull shutdown
import signal
for pid in pid_list:
os.kill(pid, signal.SIGINT)