Yocto offers the systemd class as a helper to install unit files. By default, unit files are installed on the ${systemd_unitdir}/system path on the destination directory.
When using this class, you need to specify the SYSTEMD_SERVICE_${PN} variable with the name of the unit file to install. You can optionally use the SYSTEMD_PACKAGES variable to list the packages to contain the unit files. By default, this is the main package only, and if multiple packages are provided, the SYSTEMD_SERVICE variable needs to be specified using overrides.
Services are configured to launch at boot by default, but this can be changed with the SYSTEMD_AUTO_ENABLE variable.
An example snippet is:
SYSTEMD_PACKAGES = "${PN}-syslog" SYSTEMD_SERVICE_${PN}-syslog = "busybox-syslog.service" SYSTEMD_AUTO_ENABLE = "disabled"
An example recipe, recipes-example/systemd-example/systemd-example_1.0.bb, for a simple service, is introduced next:
DESCRIPTION = "Example systemd service"
LICENSE = "MIT" LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"
SRC_URI = " file://systemd-example.service file://simple-service.c "
inherit systemd
S = "${WORKDIR}"
SYSTEMD_SERVICE_${PN} = "systemd-example.service"
do_compile () { ${CC} ${LDFLAGS} simple-service.c -o simple-service }
do_install () { install -d ${D}${bindir} install -m 0755 ${WORKDIR}/simple-service ${D}${bindir} install -d ${D}${systemd_unitdir}/system install -m 0644 ${WORKDIR}/systemd-example.service ${D}${systemd_unitdir}/system sed -i -e 's,@BINDIR@,${bindir},g' ${D}${systemd_unitdir}/system/systemd-example.service }
This recipe installs the following systemd service unit:
[Unit] Description=Example service
[Service] Type=forking ExecStart=@BINDIR@/simple-service
[Install] WantedBy=multi-user.target
It also runs a very simple daemon skeleton:
#include <unistd.h> #include <syslog.h>
#define DAEMON_NAME "simpledaemon"
int main() { setlogmask(LOG_UPTO(LOG_INFO)); openlog(DAEMON_NAME, LOG_CONS | LOG_PERROR, LOG_USER); daemon(0,0); while (1) { syslog(LOG_INFO, "daemon running"); sleep(10); } return 0; }