Pidfile Management (pid)

3.0.4 · active · verified Thu Apr 16

The `pid` library (current version 3.0.4) provides robust pidfile management capabilities, including stale detection and file-locking. It can be used as a context manager or a decorator to ensure only one instance of a process is running, and to handle cleanup of the pidfile on termination. It's a stable library with a focus on reliable process control.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates using `PidFile` as a context manager to ensure a single instance of a process is running. It attempts to create a pidfile, performs some simulated work, and automatically cleans up the pidfile upon exiting the `with` block. It also shows how to catch common exceptions if another instance is detected.

import os
import time
from pid import PidFile, PidFileAlreadyLockedError, PidFileAlreadyRunningError

def my_daemon_process():
    print("Attempting to start process...")
    try:
        # By default, creates pidfile in /var/run, or /tmp on some systems.
        # pidname defaults to script name.
        with PidFile('my_app_daemon') as p:
            print(f"Process PID: {os.getpid()} has acquired pidfile {p.path}")
            # Simulate daemon work
            for i in range(5):
                print(f"Working... {i+1}/5")
                time.sleep(1)
            print("Process finished work and released pidfile.")
    except PidFileAlreadyLockedError:
        print("Error: Another instance of the process is already running and holds the lock.")
    except PidFileAlreadyRunningError:
        print("Error: Another instance of the process is already running (pidfile exists and PID is active).")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

if __name__ == '__main__':
    my_daemon_process()

view raw JSON →