daemon

The daemon module.

class confirm.utils.daemon.Daemon

This class helps to write Python daemons on *NIX systems by using the UNIX double-fork magic and PID files.

Note

The usage of this class is quite simple. You just have to create your own class and inherit from the Daemon class and implement your business logic in the run() method like so:

from time import sleep

from confirm.utils.daemon import Daemon


class MyDaemon(Daemon):

    def run(self):
        while True:
            print('I am running')
            sleep(1)

To start the daemon, you can use the start() method:

my_daemon = MyDaemon()
my_daemon.start()

To stop it you can use the stop() method:

my_daemon = MyDaemon()
my_daemon.stop()

See also

Have a look at Advanced Programming in the Unix Environment by W. Richard Stevens & Stephen A. Rago.

change_to_root_dir: bool = True

Change to root directory when daemonising.

daemonise() → None

Daemonise the class by using the UNIX double-fork magic.

Note

This method is automatically called by the start() method.

delete_pid_file() → None

Delete the PID file.

The filename for the PID file is retreived from pid_file.

classmethod fork(number: int) → None

Fork the current process.

In case the fork doesn’t work, an error message is printed to stderr and the script exits with exit code 254.

Args:

number: The fork number (used for the error message)

handle_signals() → None

Handle the IPC signals so that the delete_pid_file() method is called before really exiting.

The PID file removal is registered by the atexit.register() method. While this works for normal exits, we also need to handle a lot of different SIG* IPC signals and do a more graceful exit than just terminating.

ignore_signals: set[Signals] = {Signals.SIGKILL, Signals.SIGCHLD, Signals.SIGCONT, Signals.SIGSTOP, Signals.SIGURG, Signals.SIGWINCH}

Set of signals to ignore.

property pid_file: str

The PID file.

By default the PID file is stored in /var/run/{classname}.pid. If you want a different PID file, feel free to overwrite this property.

restart() → None

Restart the daemon.

Note

This is a simple wrapper for calling stop() and then start().

run() → None

Run method which implements the business logic.

Raises:

NotImplementedError: When not implemented

start(daemonise: bool = True) → None

Start the daemon.

Args:

daemonise: Should the process be daemonised or not

stop() → None

Stop the daemon.

write_pid_file() → None

Write the PID file.

The filename for the PID file is retreived from pid_file.