l0andr / pylockfile

Implementation of concepts of .pid and .lock files.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

pylockfile

Python implementation of Lock (.lock) and PID (.pid) file concepts

A lock file is a file used by various operating systems and programs to lock a resource, such as a file or device. A lock file is just a file, but if it exists, it signals to other processes that the resource is already in use. The pylockfile.lockfile.LockFile class can create lock files, delete them, and raise exceptions when attempts to lock it again. This class can be used as a Context Manager or Decorator for critical code sections or functions.

A PID file is a similar concept. It is a file that is created when a process starts and deleted when the process finishes. Usually, a PID file contains the process identifier number in its name. The pylockfile.pidfile.PidFile class can create a PID file when a process starts and delete it when it ends. It can also correctly handle SIGTERM and SIGINT signals and can work as a Context Manager.

Last but not least, the signal_dispatcher module contains the pylockfile.signal_dispatcher.SignalDispatcher class. This module allows for re-assignment or addition of new handlers for system signals such as SIGTERM or SIGINT. This module is used by other modules in the package, but it can also be used separately if you need to set your own handlers for system signals.

Features:

  • LockFile and PidFile can be used as Context Managers
  • LockFile and PidFile can be used as Decorators
  • Available class SignalPidFile, it is singleton version of PidFile
  • Available .lock \ .pid file removing by handling of SIGTERM \ SIGINT signals

Example:

    import time
    import os
    from pylockfile.lockfile import LockFile
    from pylockfile.pidfile import SinglePidFile
    from pylockfile.lock_exceptions import AlreadyLocked

    with SinglePidFile(delete_lock_on_sigint=True):
        spf = SinglePidFile()
        while spf.is_locked():
            try:
                with LockFile(lockname="critical_code") as lockname:
                    print(f"I, process with PID={os.getpid()}, have caught this very critical resource")
                    # work with some critical resource
                    time.sleep(5)
            except AlreadyLocked:
                print(f"But I, process with PID={os.getpid()},can not caught this very critical resource")

            @LockFile(lockname="critical_function")
            def some_critical_function():
                time.sleep(3)
                print(f"Process with PID={os.getpid()},in some critical function")
            try:
                some_critical_function()
            except AlreadyLocked:
                print(f"Process with PID={os.getpid()},awaiting access to some critical function")

About

Implementation of concepts of .pid and .lock files.

License:MIT License


Languages

Language:Python 100.0%