Welcome, guest | Sign In | My Account | Store | Cart

Context manager for a pid (process id) file used to tell whether a daemon process is still running.

On entry, it writes the pid of the current process to the path. On exit, it removes the file.

Designed to work with python-daemon.

Python, 41 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Dual licensed under the MIT and GPL licenses.

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)

# example usage
import daemon
context = daemon.DaemonContext()
context.pidfile = PidFile("/var/run/mydaemon")

You would use this because the pid file tools that come with python-daemon are not correctly implemented as a context manager.

3 comments

Daniel O'Connor 10 years, 6 months ago  # | flag

Hi, I was wondering if you could dual license this (add the GPL) as I want to use it in an existing GPL projects (pywws).

Thanks.

Graham Poulter (author) 10 years, 6 months ago  # | flag

Hi Daniel, the MIT license is GPL-compatible, meaning you can include it in GPL projects, without affecting the license of the rest of the code. All you gain from dual-licensing is not having to include the license text (http://opensource.org/licenses/MIT) in the file defining the class. But sure, no harm, I'll edit the snippet.

Daniel O'Connor 10 years, 6 months ago  # | flag

OK, thanks very much!

Created by Graham Poulter on Mon, 17 Oct 2011 (MIT)
Python recipes (4591)
Graham Poulter's recipes (7)

Required Modules

Other Information and Tasks