Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shm_unlink from the shell?

I have a program that creates a shared memory object with shm_open that I'm working on. It tries to release the object with shm_unlink, but sometimes a programming error will cause it to crash before it can make that call. In that case, I need to unlink the shared memory object "by hand," and I'd like to be able to do it in a normal shell, without writing any C code -- i.e. with normal Linux utilities.

Can it be done? This question seems to say that using unlink(1) on /dev/shm/path_passed_to_shm_open, but the manpages aren't clear.

like image 984
Patrick Collins Avatar asked Apr 14 '16 17:04

Patrick Collins


People also ask

What is Shm_unlink?

The shm_unlink() function removes the name of the shared memory object specified by name. After removing the name, you can't use shm_open() to access the object. This function doesn't affect any references to the shared memory object (i.e. file descriptors or memory mappings).

What is POSIX shared memory?

The POSIX shared memory API allows processes to communicate information by sharing a region of memory. The interfaces employed in the API are: shm_open(3) Create and open a new object, or open an existing object. This is analogous to open(2).


1 Answers

Unlinking the file in /dev/shm will delete the shared memory object if no other process has the object mapped.

Unlike SYSV shared memory, which is implemented in the Kernel, POSIX shared memory objects are simply "files in disguise".

When you call shm_open and mmap, you can see the following in the process process map (using pmap -X):

 Address Perm   Offset Device   Inode Mapping
b7737000 r--s 00000000  00:0d 2267945 test_object

The device major and minor number correspond to the tmpfs mounted at /dev/shm (some systems mount this at /run, and then symlink /dev/shm to /run/shm).

A listing of the folder will show the same inode number:

$ ls -li /dev/shm/
2267945 -rw------- 1 mikel mikel 1 Apr 14 13:36 test_object

Like any other inode, the space will be freed when all references are removed. If we close the only program referencing this we see:

$ cat /proc/meminfo | grep Shmem
Shmem:               700 kB

Once we remove the last reference (created in /dev/shm), the space will be freed:

$ rm /dev/shm/test_object
$ cat /proc/meminfo | grep Shmem
Shmem:               696 kB

If you're curious, you can look at the corresponding files in the glibc sources. shm_directory.c and shm_directory.h generate the filename as /dev/your_shm_name. The implementations shm_open and shm_unlink simply open and unlink this file. So it should be easy to see that rm /dev/shm/your_shm_name performs the same operation,

like image 178
Mikel Rychliski Avatar answered Sep 23 '22 06:09

Mikel Rychliski