forked from python-beaver/python-beaver
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
40 additions
and
1 deletion.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import fcntl | ||
import os | ||
|
||
class PidFile(object): | ||
"""Context manager that locks a pid file. Implemented as class | ||
not generator because daemon.py is calling .__exit__() with no parameters | ||
instead of the None, None, None specified by PEP-343.""" | ||
# pylint: disable=R0903 | ||
|
||
def __init__(self, path): | ||
self.path = path | ||
self.pidfile = None | ||
|
||
def __enter__(self): | ||
self.pidfile = open(self.path, "a+") | ||
try: | ||
fcntl.flock(self.pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) | ||
except IOError: | ||
raise SystemExit("Already running according to " + self.path) | ||
self.pidfile.seek(0) | ||
self.pidfile.truncate() | ||
self.pidfile.write(str(os.getpid())) | ||
self.pidfile.flush() | ||
self.pidfile.seek(0) | ||
return self.pidfile | ||
|
||
def __exit__(self, exc_type=None, exc_value=None, exc_tb=None): | ||
try: | ||
self.pidfile.close() | ||
except IOError as err: | ||
# ok if file was just closed elsewhere | ||
if err.errno != 9: | ||
raise | ||
os.remove(self.path) |
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