Last active
April 16, 2022 10:23
-
-
Save gustavorv86/6e2569d60b5c4612141905013bf73055 to your computer and use it in GitHub Desktop.
Handling Linux process signals in Python
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
#!/usr/bin/env python3 | |
import os | |
import signal | |
import sys | |
import time | |
PROCESS_PID_FILE = "process.pid" | |
_finish = False | |
def signal_handler(signum, _frame): | |
global _finish | |
if signum == signal.SIGTERM: | |
print("signal {}, finishing...".format(signum)) | |
_finish = True | |
else: | |
print("ignore signal {}".format(signum)) | |
def is_finished(): | |
global _finish | |
return _finish | |
def main(): | |
global _finish | |
catchable_sigs = set(signal.Signals) - {signal.SIGKILL, signal.SIGSTOP} | |
for sig in catchable_sigs: | |
signal.signal(sig, signal_handler) | |
fd = open(PROCESS_PID_FILE, "w") | |
fd.write("{}".format(os.getpid())) | |
fd.close() | |
while not is_finished(): | |
print("running...") | |
time.sleep(5) | |
print("done") | |
sys.exit(0) | |
if __name__ == "__main__": | |
main() |
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
#!/usr/bin/env python3 | |
import os | |
import signal | |
import sys | |
PROCESS_PID_FILE = "process.pid" | |
def main(): | |
if not os.path.isfile(PROCESS_PID_FILE): | |
print("ERROR: {} not found.".format(PROCESS_PID_FILE)) | |
sys.exit(1) | |
fd = open(PROCESS_PID_FILE, "r") | |
pid = int(fd.read()) | |
fd.close() | |
os.kill(pid, signal.SIGTERM) | |
os.remove(PROCESS_PID_FILE) | |
sys.exit(0) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment