Skip to content

Instantly share code, notes, and snippets.

@pmalmgren
Last active Nov 6, 2020
Embed
What would you like to do?
Orphan Process Handling in Docker
"""A child process which receives a SIGTERM then waits 5 seconds to terminate"""
import sys, signal, time, os
def graceful_exit(_signum, _frame):
print(f"Child {os.getpid()}[ppid={os.getppid()}] received SIGTERM")
def run():
print(f"Hello from child {os.getpid()}")
signal.signal(signal.SIGTERM, graceful_exit)
while True:
time.sleep(0.5)
FROM python:3.9-alpine
COPY parent.py .
COPY child.py .
ENTRYPOINT ["python", "parent.py"]
"""Misbehaving parent process which does not wait for its children, do not use anywhere in production!"""
import sys, signal, os
import time
from multiprocessing import Process
from child import run
processes = []
def graceful_exit(_signum, _frame):
print("Gracefully shutting down")
for p in processes:
print(f"Shutting down process {p.pid}")
p.terminate()
sys.exit(0)
if __name__ == "__main__":
for _ in range(1):
proc = Process(target=run)
proc.start()
processes.append(proc)
print(f"Parent process started: {os.getpid()}")
signal.signal(signal.SIGTERM, graceful_exit)
signal.signal(signal.SIGINT, graceful_exit)
while True:
print("Parent still alive!")
time.sleep(0.5)
# Run these commands in a terminal to build our misbehaving application
$ docker build -t bad-parent .
$ docker run --rm -ti bad-parent
Parent process started: 1
Hello from child 6
# Run these commands in another terminal to inspect our misbehaving application
$ docker top a3cf7b6927c0
UID PID PPID ... CMD
root 294147 294129 ... python parent.py
root 294200 294147 ... python parent.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment