The Linux Programming Interface

(nextflipdebug5) #1

1114 Chapter 54


From the output, we can see that the program resized the shared memory object so
that it is large enough to hold the specified string.
Finally, we use the program in Listing 54-3 to display the string in the shared
memory object:
$ ./pshm_read /demo_shm
hello

Applications must typically use some synchronization technique to allow processes
to coordinate their access to shared memory. In the example shell session shown
here, the coordination was provided by the user running the programs one after
the other. Typically, applications would instead use a synchronization primitive
(e.g., semaphores) to coordinate access to a shared memory object.

54.4 Removing Shared Memory Objects


SUSv3 requires that POSIX shared memory objects have at least kernel persistence;
that is, they continue to exist until they are explicitly removed or the system is
rebooted. When a shared memory object is no longer required, it should be
removed using shm_unlink().

The shm_unlink() function removes the shared memory object specified by name.
Removing a shared memory object doesn’t affect existing mappings of the object
(which will remain in effect until the corresponding processes call munmap() or ter-
minate), but prevents further shm_open() calls from opening the object. Once all pro-
cesses have unmapped the object, the object is removed, and its contents are lost.
The program in Listing 54-4 uses shm_unlink() to remove the shared memory
object specified in the program’s command-line argument.

Listing 54-4: Using shm_unlink() to unlink a POSIX shared memory object
––––––––––––––––––––––––––––––––––––––––––––––––––––––– pshm/pshm_unlink.c
#include <fcntl.h>
#include <sys/mman.h>
#include "tlpi_hdr.h"

int
main(int argc, char *argv[])
{
if (argc != 2 || strcmp(argv[1], "--help") == 0)
usageErr("%s shm-name\n", argv[0]);
if (shm_unlink(argv[1]) == -1)
errExit("shm_unlink");
exit(EXIT_SUCCESS);
}
––––––––––––––––––––––––––––––––––––––––––––––––––––––– pshm/pshm_unlink.c

#include <sys/mman.h>

int shm_unlink(const char *name);
Returns 0 on success, or –1 on error
Free download pdf