Last active
May 7, 2018 10:07
-
-
Save beanyoung/6753345 to your computer and use it in GitHub Desktop.
Ensure that only one instance running
This file contains 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/python | |
# -*- coding: utf-8 -*- | |
import fcntl | |
from functools import wraps | |
import os | |
def singleton(pid_filename): | |
def decorator(f): | |
@wraps(f) | |
def decorated(*args, **kwargs): | |
pid = str(os.getgid()) | |
pidfile = open(pid_filename, 'a+') | |
try: | |
fcntl.flock(pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) | |
except IOError: | |
raise SystemExit('Already running!') | |
pidfile.seek(0) | |
pidfile.truncate() | |
pidfile.write(pid) | |
pidfile.flush() | |
pidfile.seek(0) | |
ret = f(*args, **kwargs) | |
try: | |
pidfile.close() | |
except IOError, err: | |
if err.errno != 9: | |
raise | |
os.remove(pid_filename) | |
return ret | |
return decorated | |
return decorator | |
@singleton('/tmp/main.pid') | |
def main(): | |
pass | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment