-
-
Save tkhn/b8e899e728495596dba18355fa4d65ed to your computer and use it in GitHub Desktop.
Singleton Process with PID Lock File #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
import os | |
import fcntl | |
import contextlib | |
import time | |
@contextlib.contextmanager | |
def lockpidfile(filepath): | |
with os.fdopen( | |
os.open(filepath, os.O_RDWR | os.O_CREAT, mode=0o666), | |
mode="r+", | |
buffering=1, | |
encoding="utf-8", | |
newline="", | |
) as f: | |
try: | |
fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB) | |
except OSError: | |
yield False | |
return | |
f.truncate() | |
pid = os.getpid() | |
f.write(f"{pid}\n") | |
yield True | |
fcntl.lockf(f, fcntl.LOCK_UN) | |
try: | |
os.unlink(filepath) | |
except OSError: | |
pass | |
def main(): | |
with lockpidfile("/tmp/lockpidfile.pid") as lockpidstatus: | |
if not lockpidstatus: | |
print("NOT GOOD - PROCESS ALREADY STARTED") | |
else: | |
print("OK!") | |
time.sleep(15) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment