Skip to content

Instantly share code, notes, and snippets.

@tkhn
Forked from CMCDragonkai/lockpidfile.py
Created January 19, 2022 15:20
Show Gist options
  • Save tkhn/b8e899e728495596dba18355fa4d65ed to your computer and use it in GitHub Desktop.
Save tkhn/b8e899e728495596dba18355fa4d65ed to your computer and use it in GitHub Desktop.
Singleton Process with PID Lock File #python
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