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 = True

Change to root directory when daemonising.

daemonise()

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

Note

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

delete_pid_file()

Delete the PID file.

The filename for the PID file is retreived from pid_file.

classmethod fork(number)

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.

Parameters:

number (int) – The fork number (used for the error message)

handle_signals()

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 = {Signals.SIGKILL, Signals.SIGCHLD, Signals.SIGCONT, Signals.SIGSTOP, Signals.SIGURG, Signals.SIGWINCH}

Set of signals to ignore.

property pid_file

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.

Returns:

The PID file

Return type:

str

restart()

Restart the daemon.

Note

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

run()

Run method which implements the business logic.

Raises:

NotImplementedError – When not implemented

start(daemonise=True)

Start the daemon.

Parameters:

daemonise (bool) – Should the process be daemonised or not

stop()

Stop the daemon.

write_pid_file()

Write the PID file.

The filename for the PID file is retreived from pid_file.