Arie Bregman

Linux And Stuff

Python: Run daemon process

What is a daemon?

Except for nature spirit, a daemon is also a process running in the background, meaning it’s a non-interactive program. It’s detached from the terminal of an interactive user.

There is no easy way to identify which processes on the system are daemonas. It’s common to think that processes with ppid (parent pid) of 1 are daemons, but you can easily create in your terminal interactive process with ppid of 1, meaning not all processes with ppid 1 are daemons.

For Windows folks, it’s common to think of daemon as a service, but in *nix service is only a command to control init scripts.

How to run a daemon process using Python?

There are several ways to achieve that.

The daemon library

Start by importing the daemon library

Next, we run our service as a daemon

We used ‘with’ statement to manage this resource properly by entering _enter_ method. When the daemon finishes to run it will enter the __exit__ method.

The pidfile is the context manager for the pid lock file. So entering and existing the daemon context will go through the pidfile context.

This is probably the best approach for running daemons with Python.

The long way

I see no reason for you to not use the daemon library, but let’s take a look on how to do it without it, just for fun.

Let’s start by creating the Daemon class

When creating a Daemon instance, you should pass a pidfile parameter, which is the  path to the pid lock file.

Next, let’s add method to the class which will start to run the daemon (if it’s not already running):

Next,  let’s add the method ‘run’ to handle the forking and write the pid to the pid lock file.

This is the fork method implemention

Finally, you can start running a daemon by writing the following lines

Of course you can, and probably should, add methods to allow stopping the daemon or restarting it.


  1. Hey Arie,

    I had to deal with daemons recently and found out that some implementations (e.g. in OpenStack) use a double fork approach [1]. Basically it’s to ensure that init will take care of its cleanup and it’ll never acquire a tty.

    Great blog, keep up the good work! :=)


    • bregman

      December 28, 2016 at 3:02 pm

      Thanks Daniel, interesting stuff.

      If you can, I would appreciate a reference link to such approach in OpenStack code 🙂

Leave a Reply

Your email address will not be published.


© 2018 Arie Bregman

Theme by Anders NorenUp ↑