In the previous post we have seen how to start a simple deamon with systemd. Now we will use the socket based activation of this init system to make our daemon start when it is needed.
Let’s start with a basic server which only prints a message.
This code is based on the CommonLib library.
Now, if systemd started us, we need to get the listening file descriptor and to do so with must include the systemd header file:
and to replace:
The sd_listen_fds function will count the sockets passed by systemd and, if systemd started us, the file descriptor SD_LISTEN_FDS_START + 0, the first, is encapsulated in a TCPListenSocket object. The server then follows in the same way. Simple, isn’t?
Now our server is socket activatable. We must tell it to systemd writing a my_server.socket like this:
We must also write a my_server.service file like this:
Note that this service file has not the install section.
These files must be placed in our /usr/lib/systemd/system directory.
We can make systemd preallocate the socket for us with:
If you ask your system for the running processes you will not see the daemon process.
When you will make the first connection systemd will start it.