Skip to content

Instantly share code, notes, and snippets.

@BafDyce
Created August 13, 2016 08:33
Show Gist options
  • Save BafDyce/36eabef71b1c9088a34aa24fe56c670b to your computer and use it in GitHub Desktop.
Save BafDyce/36eabef71b1c9088a34aa24fe56c670b to your computer and use it in GitHub Desktop.
""" Uses the posix_ipc module (https://pypi.python.org/pypi/posix_ipc) to
ensure that only one instance of the program is running. It catches all kind
of "errors" (namely Ctrl+C, SIGINT, SIGTERM, and any exception raised in the
program) in order to ensure no ressource leaks.
Probably works only on Linux (due to the posix_ipc library). """
#!/usr/bin/python3
import signal
import sys
import posix_ipc
from util.getch import getch
SEMAPHORE_NAME_MAIN = "YOUR_NAME_FOR_THE_SEMAPHORE_HERE"
semaphore_main = ""
def init():
global semaphore_main
""" Check whether a daemon is already running """
try:
semaphore_main = posix_ipc.Semaphore(SEMAPHORE_NAME_MAIN)
semaphore_main.release()
semaphore_main.close()
print("There's already another instance of this program running.")
return False
except posix_ipc.ExistentialError:
print("I'm the first instance of this program!")
semaphore_main = posix_ipc.Semaphore(SEMAPHORE_NAME_MAIN, posix_ipc.O_CREX)
""" Finally, register signal handlers to prevent ressource leaks when
receiving SIGINT & co. """
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
return True
return False
def cleanup():
global semaphore_main
try:
semaphore_main.release()
semaphore_main.unlink()
except posix_ipc.ExistentialError:
""" This exception could be raised if we called cleanup() more than
once.. """
pass
def signal_handler(signum, frame):
print("Received a signal ({}). Shutting down gracefully..\n\r".format(signum))
cleanup()
sys.exit(0)
def run():
print("Program started successfully")
print("press any key to quit")
""" your code here! """
sys.stdin.read(1)
def main():
if init():
try:
run()
except KeyboardInterrupt:
print("Keyboard interrupt. Shutting down")
except SystemExit:
""" happens when a signal was caught """
pass
except:
print("An unexpected error occured. This is most likely a bug.",
"Nevertheless, I'll try to cleanly shut down.",
"\n", sys.exc_info())
finally:
cleanup()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment