[systemd-devel] How to run forking daemon with systemd in correct way, without errors?
Michael Chapman
mike at very.puzzling.org
Thu Nov 23 10:53:17 UTC 2017
On Thu, 23 Nov 2017, Gena Makhomed wrote:
> On 23.11.2017 7:45, Mantas Mikulėnas wrote:
>
>>> This is bug in nginx code? And this bug should be fixed in nginx?
>>>
>>> But "daemon(); write_pidfile();" is common pattern
>>> used by many services and even in library functions.
>
>> It may be common, but not necessarily correct. The parent process should
>> only exit *after* finishing all the preparations (i.e. something like
>> "fork(); write_pidfile(); exit()"), since systemd uses the exit as a signal
>> that the daemon is now "ready".
>
> You are joking? Why you think that this pattern is not correct?
Based on my understanding of the code, Type=forking services are not
deemed to be active until it sees _both_ the process has exited and the
PID file has appeared (so long as systemd is actually told about the PID
file, of course).
It should not matter whether a Type=forking service's initial process
exits first or writes its PID file first. If the PID file is missing when
the process exits, systemd will log a "PID file ... not readable (yet?)"
message, and it will keep the service in an "activating" state until it
actually becomes readable.
In short, either design should work correctly.
However, there is something to be said for only writing out the PID file
after the initial process has confirmed the service is operating
correctly. This is possible with fork() (and some kind of IPC or signal
between the child process and the original process) but not with daemon().
daemon() always exits successfully, which means other process managers
that don't PID files like systemd does would assume the process had
started successfully, even if the service's child process died straight
away.
Many other deficiencies with the BSD daemon() function are documented in
systemd's daemon(7) manpage.
I would suggest ignoring some other commenters suggestions that PID files
are unnecessary with systemd. Indeed, there's even a TODO item for a
Type=pid-file service that would, presumably, allow even non-forking
services to signal readiness by writing a PID file. I would find something
like that very useful.
More information about the systemd-devel
mailing list