Skip to content

Instantly share code, notes, and snippets.

@beanyoung
Last active May 7, 2018 10:07
Show Gist options
  • Save beanyoung/6753345 to your computer and use it in GitHub Desktop.
Save beanyoung/6753345 to your computer and use it in GitHub Desktop.
Ensure that only one instance running
#!/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