Blog/Home is where your screen session is
In this article I want to take a small note on how I configured a systemd unit to automatically start a detatched screen session.
I want to always have a screen session started for my users (mainly root and my unprivileged users).
Enable the systemd user instance.
Run (as root): loginctl enable-linger myuser
.
This will enable the startup of an unprivileged systemd session. It will automatically start user units.
Create the user unit
Make sure the unit directory exists: mkdir -p ~/.config/systemd/user
Create the file name ~/.config/systemd/user/screen-default.service
with the following contents:
[Unit]
Description=Default Screen session
Wants=default.target
After=default.target
[Service]
Type=simple
ExecStart=screen -DmS default
Restart=always
RestartSec=3
StartLimitBurst=1
[Install]
WantedBy=default.target
Enable and start
As simple as running systemctl --user enable --now screen-default.service
Screen parameters details
This is interesting:
- -D start screen in detached mode, but does not perform e fork before starting
- This means that the main process will not exit (and systemd will be able to track it)
- screen wil exit when the session terminates
- -d would perform a fork
- -m ignores the $TTY environment variable, so it will not complain
- -s default sets the session name to default
Other interesting parameters
The Restart/RestartSec/StartLimitBurts make it possible for systemd to always restart the unit.
Meaning that there will always be a screen session ready.
A copy-paste ready version
So I've done it a few times and I guess it's better to have a single copy-paste ready version
# sudo loginctl enable-linger `whoami`
mkdir -p ~/.config/systemd/user
cat > ~/.config/systemd/user/screen-default.service <<EOF
[Unit]
Description=Default Screen session
Wants=default.target
After=default.target
[Service]
Type=simple
ExecStart=screen -DmS default
Restart=always
RestartSec=3
StartLimitBurst=1
[Install]
WantedBy=default.target
EOF
systemctl --user enable --now screen-default.service