Search code examples
postgresqlubuntuipcshared-memorysystemd

Why Systemd remove my SHM file but not Postgresql's?


I'm developing a daemon application on Ubuntu server that being managed by Systemd.

I create a SHM file in /dev/shm/ by using shm_open, and close the file descriptor after calling to mmap. At the beginning it exists, but it disappeared after a time, maybe as I loged out from the server.

Perhaps this is controlled by the option RemoveIPC=yes in /etc/systemd/logind.conf.

My question is

  1. Why does systemd not clean up the shm file created by Postgresql, but mine?
  2. How to modify my app to make it like Postgresql, so that we can reduce the managing/maintaining work at the producing time.
  3. I found that the shm memory is still available after it be cleaned by systemd. Does this mean that I can ignore that, and continue to use it without recreating?

Solution

  • I think your suspicion is right; see the documentation for details:

    If systemd is in use, some care must be taken that IPC resources (including shared memory) are not prematurely removed by the operating system. This is especially of concern when installing PostgreSQL from source. Users of distribution packages of PostgreSQL are less likely to be affected, as the postgres user is then normally created as a system user.

    The setting RemoveIPC in logind.conf controls whether IPC objects are removed when a user fully logs out. System users are exempt. This setting defaults to on in stock systemd, but some operating system distributions default it to off. [...]

    A “user logging out” might happen as part of a maintenance job or manually when an administrator logs in as the postgres user or something similar, so it is hard to prevent in general.

    What is a “system user” is determined at systemd compile time from the SYS_UID_MAX setting in /etc/login.defs.

    Packaging and deployment scripts should be careful to create the postgres user as a system user by using useradd -r, adduser --system, or equivalent.

    Alternatively, if the user account was created incorrectly or cannot be changed, it is recommended to set

    RemoveIPC=no
    

    in /etc/systemd/logind.conf or another appropriate configuration file.

    While this is talking about PostgreSQL, the same applies to your software. So take one of the recommended measures.