systemd (new style) daemon in C/C++

Viewed 645

On the Internet there are multiple code example which explains how to write the old style daemon in pure C or even in C++.

However, there is no such thing for a "new style" (or systemd one).

Is there a basic "simple daemon" code I can re-use to write a "new style" systemd daemon in C/C++?

1 Answers

I have many examples in my Snap! C++ environment. Look for the *.service files under the snapwebsites/debian directory to find the projects that act as a daemon.

More or less, you write a tool that opens a port to listen on and handle the messages you receive. The rest is taken care of by systemd.

Here is an example used by the snapfirewall daemon:

# Documentation available at:
# https://www.freedesktop.org/software/systemd/man/systemd.service.html

[Unit]
Description=Snap! Websites snapfirewall daemon
After=snapbase.service snapcommunicator.service snapdbproxy.service
Before=fail2ban.service
[Service]
Type=simple
WorkingDirectory=~
ProtectHome=true
# snapfirewall needs to run iplock which setuid to root so we can't set
# this parameter to true
NoNewPrivileges=false
ExecStart=/usr/sbin/snapfirewall
ExecStop=/usr/bin/snapstop --service "$MAINPID"
Restart=on-failure
RestartSec=1min
User=snapwebsites
Group=snapwebsites
LimitNPROC=1000
# For developers and administrators to get console output
#StandardOutput=tty
#StandardError=tty
#TTYPath=/dev/console
# Enter a size to get a core dump in case of a crash
#LimitCORE=10G

[Install]
WantedBy=multi-user.target

# vim: syntax=dosini

As mentioned at the top, the service unit documentation is found on freedesktop.

In this one, I have a NoNewPrivileges=false parameter. This means the suid will work as expected. Otherwise my tool could not add/remove rules to the firewall since the snapfirewall runs as the snapwebsites user, which can't run iptables at all.

That's pretty much all there is to it.

Note: The advantage of using a debian directory and building your own package is that it will automatically generate all the necessary scripts to start/enable/stop your service as expected. The only trick on this one is that the debian/rules must include the --with systemd command line option. But outside of that, it's going to be a breeze.

Related