============
test.sh
============
#!/bin/bash
_term() {
echo "SHELL: Caught SIGTERM signal, propagating to the child"
kill -TERM "$child" 2>/dev/null
}
trap _term SIGTERM
python3 test.py &
child=$!
wait "$child"
exit_status=$?
trap - SIGTERM
wait "$child"
if test ${exit_status} -eq 0; then
echo "SHELL: Task finished.";
else
echo "SHELL: Task failed.";
exit ${exit_status}
fi
============
test.py
============
import time
import sys
import signal
import time
class GracefulKiller:
kill_now = False
def __init__(self):
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
def exit_gracefully(self,signum, frame):
self.kill_now = True
if __name__ == '__main__':
killer = GracefulKiller()
while True:
print("== going to sleep ==")
time.sleep(30)
print("== woken up ==")
if killer.kill_now:
break
print("End of the program. I was killed gracefully :)")
Rahul Gupta