Systemd unit file howto
I’ve searched the Internet for simple howtos on how to write a systemd service file from scratch but I haven’t found any, so here it is: a howto on writing minimal service files for embedded systems processes.
You may want to familiarize with some basic concepts before going on.
A service file is very similar to an INI file in its structure. A basic file has 3 sections: Unit, Service and Install
[Unit]
Basic information about the service. The most important entries are:
Description: a simple description of your process;
Wants: list all services that are needed for this process. If your program uses socket or dbus activation the dependencies are automatic and you don’t need this entry;
After: wait for the listed services to go up before starting your process. Again, this is only needed in case you are not using socket or dbus activation.
[Service]
This section actually specifies the executable you want to launch and the running behaviour. The most important entries are:
ExecStart: the absolute path of the executable to start;
Environment: use this to set relevant environment variables for your process. Example
Environment=EGLFS_HIDE_CURSOR=1 “POINTERCAL_FILE=/path/with spaces/pointercal”
Note that in case of spaces the double quotes enclose also the variable name.
Type: it’s used by systemd to guess which process is the “main” process. Particularly useful when daemons fork a couple of times; not really useful if you just have a single application that you want to launch, set it to simple;
Restart: configure how/when your service should be restarted. For embedded systems always is a reasonable choice;
SuccessExitStatus: a list of signals or numbers (other than 0) that indicate a successful exit status.
By the way, multiple forking is the standard way to daemonize from shell, read the docs for more information.
[Install]
This section is useful if you want to enable or disable your service. In systemd parlance, a service is enabled if it automatically starts at boot; you usually want this for embedded systems. Mainly this boils down to:
[Install]
WantedBy=multi-user.target
Complete example
Here is a complete example of a standalone application that we want to start at boot:
[Unit] Description=Description for myprogram Wants=rpcbind.service After=rpcbind.service
[Service] Environment="MY_ENV_VAR=/some/path/to/file with space.ini" ExecStart=/usr/local/myprogram Type=simple
[Install] WantedBy=multi-user.target
Documentation
Official systemd documentation
Unit file variables












