Creating daemons in Linux is quite complex issue, but it’s very well documented in daemon(7) manual
. Thankfully there is python-daemon
module for Python 2 and 3 that implement PEP3143, so I’m using it.
Here comes the question: when I was playing with python-daemon
module I was surprised that daemon’s PPID is not 1
. Why?
Simple example:
import daemon import time import os with open('/tmp/test.log', 'w') as logfile: c = daemon.DaemonContext(stdout=logfile) with c: print('In daemon...') for i in range(10): print('My PID is {}, PPID is {}'.format(os.getpid(), os.getppid())) time.sleep(2)
Content of test.log
after 20 seconds from starting the above script (I recommend tail -f /tmp/test.log
):
In daemon... My PID is 31397, PPID is 1736 My PID is 31397, PPID is 1736 My PID is 31397, PPID is 1736 My PID is 31397, PPID is 1736 My PID is 31397, PPID is 1736 My PID is 31397, PPID is 1736 My PID is 31397, PPID is 1736 My PID is 31397, PPID is 1736 My PID is 31397, PPID is 1736 My PID is 31397, PPID is 1736
It turned out that process with PID 1736
is /lib/systemd/systemd
:
patryk@mycomp:/tmp$ ps -fq 1736 UID PID PPID C STIME TTY TIME CMD patryk 1736 1 0 kwi12 ? 00:00:00 /lib/systemd/systemd --user
Recently I was implementing daemons in C
(on the same machine with systemd
installed) and AFAIR all daemons had PPID = 1
. All manuals I came across mention that daemon’s PPID is always 1
.
Does systemd
changed it? Does systemd
process awaits
for all processes – including daemons? Is it daemon’s correct behavior?
Related questions:
- How do you create a daemon in Python?
- How do I set up a daemon with python-daemon?
- How to make a Python script run like a service or daemon in Linux
- Python 3.3.4: python-daemon-3K ; How to use runner
Advertisement
Answer
The short answer is: It doesn’t matter.
The important thing is that all daemons have a parent process like init
that will reap children when they die, by calling wait()
. Otherwise the process will become a zombie when it exits.
There’s nothing particularly special about having a parent PID of 1. The manual page you linked to says this process is PID 1 for old, SysV-style daemons, but doesn’t say so for new SystemD-style daemons. init
always runs as PID 1, and traditionally it was the parent of daemons. But it doesn’t need to be so.
systemd --user
manages user services. Thus, it makes sense why this process becomes your daemon’s parent process when you run it (as a user).
One must be careful when reading documentation about *nix, a platform that’s been around for decades. Things change and manuals become obsolete, or can be interpreted in the wrong context. SystemD brings major change to a lot of things about the Linux platform.