Skip to content
systemcoding.dev
Systems Programming

List and Remove Stale IPC Objects with ipcs and ipcrm

Find and remove leftover System V and POSIX IPC objects with ipcs and ipcrm: read the tables, spot orphans by nattch, delete by id or key and clean /dev/shm.

7 min read
Summarize in AI
Flat illustration of a magnifier over lines of a log, with the Linux, GNU and C++ logos.

A crashed program leaves behind shared memory segments, message queues and semaphores that nobody owns, and they sit in kernel memory until the machine reboots. Over weeks they pile up, a new run fails with No space left on device from shmget(), or an old segment's contents confuse the next start. ipcs lists these objects and ipcrm removes them. This post shows how to read the listing, decide what is safe to delete and clean both families, on Linux 6.12 with util-linux 2.41, following ipcs(1) and ipcrm(1).

The objects are created by the System V calls in use System V shared memory with shmget and shmat and its neighbors, and by the POSIX calls in share memory between processes with shm_open and mmap. The two families live in different places and need different tools.

Why they leak

Pipes and sockets vanish when their last descriptor closes. Shared memory, semaphores and message queues are kernel objects with their own lifetime. A program must remove them explicitly, with shmctl(IPC_RMID), msgctl(IPC_RMID), semctl(IPC_RMID) for System V, and shm_unlink(), sem_unlink() and mq_unlink() for POSIX. A program that crashes, is killed with SIGKILL or forgets leaves them in place. The kernel does not know whether anyone intends to use them again.

Reading ipcs

ipcs with no options prints all three System V tables. Each section is one object type.

Shell
ipcs
Text

------ Message Queues --------
key        msqid      owner      perms      used-bytes   messages
0x2a0b1c3d 0          user       600        0            0

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status
0x00000000 32768      user       600        524288     2          dest
0x1b2c3d4e 32769      user       666        4096       0
0x00000000 32770      user       600        67108864   0

------ Semaphore Arrays --------
key        semid      owner      perms      nsems
0x3c4d5e6f 0          user       600        3

The columns:

ColumnMeaning
keyThe numeric key given to shmget(), msgget() or semget(). 0x00000000 is IPC_PRIVATE, and it has no name
shmid, msqid, semidThe identifier the system assigned. This is what ipcrm takes
ownerThe user that created the object
permsOctal permission bits, as for a file
bytesSegment size
nattchNumber of processes currently attached to the segment
statusdest means marked for destruction, and it will go when the last process detaches
used-bytes, messagesContent of a message queue
nsemsSemaphores in the array

The identifiers shown here are an example, since they differ on every system.

Spotting the orphans

A shared memory segment with **nattch of 0** has no processes attached. It may be an orphan, or it may belong to a service that is between runs and expects to find it again. A segment with nattch above 0 is in use, and you must not remove it from under a running process. A dest flag means a process has already asked for its destruction and it lingers only because someone is still attached.

For a message queue, used-bytes and messages above zero mean unread data. Semaphore arrays have no usage counter, which makes them harder to judge, and the usual way is to find which program owns the key.

To decide, find the owner program. ipcs -m -p shows the creator and last operator PIDs (cpid, lpid), and if neither is alive, the object is abandoned. ipcs -m -t shows attach, detach and change times, and a segment untouched for months with nattch 0 is a likely orphan. ipcs -m -c shows creator and owner, ipcs -l prints the system limits and ipcs -u summarizes usage.

Shell
ipcs -m -p
Text

------ Shared Memory Creator/Last-op PIDs --------
shmid      owner      cpid       lpid      
32768      user       4121       4130      
32769      user       3104       3104      
32770      user       2297       2297      

If ps -p 3104 and ps -p 2297 show nothing, the segments 32769 and 32770 were left by processes that no longer exist. PIDs are reused, so a live process with the same number is not proof of ownership. Compare with ps -o lstart= -p PID against the segment's creation time from ipcs -m -t.

Removing objects

ipcrm takes a type and either an id or a key.

Shell
ipcrm -m 32770      # remove a shared memory segment by id
ipcrm -M 0x1b2c3d4e # remove one by key
ipcrm -q 0          # remove a message queue by id
ipcrm -s 0          # remove a semaphore array by id

A plain run prints nothing on success. Removing an unknown id prints an error like ipcrm: invalid id (32770). Removing a segment that is still attached does not free it at once: it is marked dest and disappears when the last process detaches, so the command is safe in that sense, but it breaks any later attempt to attach by key.

You can only remove objects you own, unless you are root or have the right capability. Trying to remove another user's returns Operation not permitted.

Newer util-linux versions (2.23 and later) also offer bulk forms: ipcrm --all=shm, ipcrm --all=msg, ipcrm --all=sem and ipcrm --all, which remove everything of that type that you are allowed to remove. These are blunt tools, and on a shared machine or a host running databases they delete other programs' state. Use them only in disposable environments such as a CI worker.

A careful script for unattached segments

To remove only your own segments that have no attached process, filter the table. The $2 column is the id and $6 is nattch in the segment table.

Shell
ipcs -m | awk -v me="$USER" '$3 == me && $2 ~ /^[0-9]+$/ && $6 == 0 { print $2 }' | xargs -r -n1 ipcrm -m

This prints nothing and removes every segment owned by you with zero attached processes. Read the list first by running the pipeline without the last xargs stage, and only then delete. Be careful on a machine running services under your user name, because some programs, notably some databases and window systems, keep segments with nattch zero between operations and expect them to be there when they run next.

The POSIX family is elsewhere

ipcs does not show POSIX objects at all. They appear as files:

Shell
ls -l /dev/shm /dev/mqueue
Text
/dev/mqueue:
total 0
-rw------- 1 user user 80 Nov 23 12:20 jobs

/dev/shm:
total 4
-rw------- 1 user user  104 Nov 23 12:05 demo_counter
-rw------- 1 user user   32 Nov 23 12:11 sem.ping

POSIX shared memory objects are plain files in /dev/shm, named semaphores are files with a sem. prefix in the same directory, and message queues are in /dev/mqueue if the mqueue filesystem is mounted. Remove them with rm, since rm calls the same unlink() that shm_unlink() does, or with sem_unlink() and mq_unlink() from code. Because they are files, the usual tools work: ls -l shows owner and size, lsof /dev/shm/demo_counter shows which processes have them mapped and fuser lists the processes.

Shell
lsof /dev/shm/demo_counter
Text
COMMAND  PID USER  FD   TYPE DEVICE SIZE/OFF  NODE NAME
worker  4410 user mem    REG   0,26      104 11230 /dev/shm/demo_counter

No output means nothing has it mapped, and it is safe to remove if you know the program is not going to need the contents.

Limits you may hit

A leaked segment accumulates against kernel limits. ipcs -l prints them, and they come from /proc/sys/kernel/: shmmax (largest segment), shmall (total pages), shmmni (number of segments, 4,096 by default), msgmni and sem (four numbers: semaphores per set, total, operations per call and number of sets). When shmget() fails with ENOSPC, shmmni was reached, and when it fails with ENOMEM memory or shmall is the cause. Cleaning leaks is the first response, and raising limits with sysctl is the second.

Preventing the leak

Cleanup belongs in the program. Three habits remove most leaks:

  1. Remove at creation if you can. For System V shared memory shared between a parent and its children, call shmctl(id, IPC_RMID, NULL) immediately after every process has attached, so the segment disappears automatically when the last one exits, however it exits. For POSIX, unlink right after the peers have opened the name.

  2. Handle termination signals and clean up in the main loop, with the flag pattern from write async-signal-safe signal handlers. This does not help against SIGKILL.

  3. Use a start-up sweep. On launch, remove stale objects with your own key or name from a previous crash, before creating new ones.

When not to delete

Do not remove an object you do not recognize on a production machine. If it has a nonzero nattch, a recent change time or an owner you do not know, find out first. If a service creates its segments with fixed keys and keeps them across restarts, deleting one forces a cold start and may lose cached state. And ipcrm --all is the wrong tool anywhere other than a throwaway environment.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.