78

I had a daemon that needed its own dir in /var/run for its PID file with write permission granted to the daemon's user.

I found I could create this dir with these commands:

# mkdir /var/run/mydaemon

Then I could change its ownership to the user/group under which I wished to run the process:

# chown myuser:myuser /var/run/mydaemon

But this dir would be GONE whenever I issue a reboot! How do I get this dir to create every time the machine boots?

HBruijn
  • 84,206
  • 24
  • 145
  • 224
user24601
  • 1,043

2 Answers2

125

There are two alternatives.

One is to declare a RuntimeDirectory in the systemd unit file of your service. Example:

RuntimeDirectory=foo

This will create /run/foo when the underlying systemd service starts. (Note: DO NOT provide a full path, just the path under /run) For full docs please see the appropriate entry in systemd.exec docs. Setting permissions or user/group ownership is a bit difficult (sometimes impossible) this way, but for a basic usage it works well. The directory is also automatically removed once the systemd service stops.


Alternatively, configure the automatic creation of such directories or files using tmpfiles.d. For example, /etc/tmpfiles.d/mydaemon.conf :

#Type Path            Mode UID      GID    Age Argument
d     /run/mydaemon   0755 myuser myuser   -   -

The dir will be created at boot, or if you run systemd-tmpfiles --create manually. If you are a packager for an OS, not a local user, then such a file should be put in /usr/lib/tmpfiles.d instead. See the full tmpfiles.d docs here.

HBruijn
  • 84,206
  • 24
  • 145
  • 224
8

I created a service that would make the dir at start:

vim /etc/systemd/system/mydaemon-helper.service

The contents of /etc/systemd/system/mydaemon-helper.service:

[Unit]
Description=MyDaemon Helper Simple Service
After=network.target

[Service]
Type=simple
ExecStartPre=-/usr/bin/mkdir /var/run/mydaemon
ExecStart=/usr/bin/chown myuser:myuser /var/run/mydaemon
Restart=on-abort


[Install]
WantedBy=multi-user.target

Then I started this service:

systemctl start mydaemon-helper

systemctl status mydaemon-helper

Output:

[root@alpha etc]# systemctl status mydaemon-helper.service
● mydaemon-helper.service - MyDaemon Helper Simple Service
   Loaded: loaded (/etc/systemd/system/mydaemon-helper.service; disabled; vendor preset: disabled)
   Active: inactive (dead)

May 28 20:53:50 alpha systemd[1]: Starting MyDaemon Helper Simple Service...
May 28 20:53:50 alpha systemd[1]: Started MyDaemon Helper Simple Service.

Lastly I told the system to load it on startup:

systemctl enable mydaemon-helper

user24601
  • 1,043