1 .\" Copyright (C) 2002, 2020 Michael Kerrisk <mtk.manpages@gmail.com>
3 .\" %%%LICENSE_START(VERBATIM)
4 .\" Permission is granted to make and distribute verbatim copies of this
5 .\" manual provided the copyright notice and this permission notice are
6 .\" preserved on all copies.
8 .\" Permission is granted to copy and distribute modified versions of this
9 .\" manual under the conditions for verbatim copying, provided that the
10 .\" entire resulting derived work is distributed under the terms of a
11 .\" permission notice identical to this one.
13 .\" Since the Linux kernel and libraries are constantly changing, this
14 .\" manual page may be incorrect or out-of-date. The author(s) assume no
15 .\" responsibility for errors or omissions, or for damages resulting from
16 .\" the use of the information contained herein. The author(s) may not
17 .\" have taken the same level of care in the production of this manual,
18 .\" which is licensed free of charge, as they might when working
21 .\" Formatted or processed versions of this manual, if unaccompanied by
22 .\" the source, must acknowledge the copyright and authors of this work.
25 .TH SHM_OPEN 3 2021-03-22 "Linux" "Linux Programmer's Manual"
27 shm_open, shm_unlink \- create/open or unlink POSIX shared memory objects
30 .B #include <sys/mman.h>
31 .BR "#include <sys/stat.h>" " /* For mode constants */"
32 .BR "#include <fcntl.h>" " /* For O_* constants */"
34 .BI "int shm_open(const char *" name ", int " oflag ", mode_t " mode );
35 .BI "int shm_unlink(const char *" name );
38 Link with \fI\-lrt\fP.
41 creates and opens a new, or opens an existing, POSIX shared memory object.
42 A POSIX shared memory object is in effect a handle which can
43 be used by unrelated processes to
45 the same region of shared memory.
48 function performs the converse operation,
49 removing an object previously created by
54 is analogous to that of
57 specifies the shared memory object to be created or opened.
59 a shared memory object should be identified by a name of the form
61 that is, a null-terminated string of up to
63 (i.e., 255) characters consisting of an initial slash,
64 .\" glibc allows the initial slash to be omitted, and makes
65 .\" multiple initial slashes equivalent to a single slash.
66 .\" This differs from the implementation of POSIX message queues.
67 followed by one or more characters, none of which are slashes.
68 .\" glibc allows subdirectory components in the name, in which
69 .\" case the subdirectory must exist under /dev/shm, and allow the
70 .\" required permissions if a user wants to create a shared memory
71 .\" object in that subdirectory.
74 is a bit mask created by ORing together exactly one of
78 and any of the other flags listed here:
81 Open the object for read access.
82 A shared memory object opened in this way can be
89 Open the object for read-write access.
92 Create the shared memory object if it does not exist.
93 The user and group ownership of the object are taken
94 from the corresponding effective IDs of the calling process,
95 .\" In truth it is actually the filesystem IDs on Linux, but these
96 .\" are nearly always the same as the effective IDs. (MTK, Jul 05)
98 permission bits are set according to the low-order 9 bits of
100 except that those bits set in the process file mode
103 are cleared for the new object.
104 A set of macro constants which can be used to define
108 (Symbolic definitions of these constants can be obtained by including
111 A new shared memory object initially has zero length\(emthe size of the
112 object can be set using
114 The newly allocated bytes of a shared memory
115 object are automatically initialized to 0.
120 was also specified, and a shared memory object with the given
122 already exists, return an error.
123 The check for the existence of the object, and its creation if it
124 does not exist, are performed atomically.
127 If the shared memory object already exists, truncate it to zero bytes.
129 Definitions of these flag values can be obtained by including
132 On successful completion
134 returns a new file descriptor referring to the shared memory object.
135 This file descriptor is guaranteed to be the lowest-numbered file descriptor
136 not previously opened within the process.
141 is set for the file descriptor.
143 The file descriptor is normally used in subsequent calls
146 (for a newly created object) and
150 the file descriptor may be closed without affecting the memory mapping.
157 it removes a shared memory object name, and, once all processes
158 have unmapped the object, deallocates and
159 destroys the contents of the associated memory region.
164 an object with the same
168 was specified, in which case a new, distinct object is created).
172 returns a file descriptor (a nonnegative integer).
176 On failure, both functions return \-1 and set
178 to indicate the error.
184 the shared memory object was denied.
187 Permission was denied to
194 was specified and the caller does not have write permission on the object.
203 and the shared memory object specified by
215 The per-process limit on the number of open file descriptors has been reached.
224 The system-wide limit on the total number of open files has been reached.
227 An attempt was made to
231 that did not exist, and
236 An attempt was to made to
242 These functions are provided in glibc 2.2 and later.
244 For an explanation of the terms used in this section, see
252 Interface Attribute Value
256 T} Thread safety MT-Safe locale
262 POSIX.1-2001, POSIX.1-2008.
264 POSIX.1-2001 says that the group ownership of a newly created shared
265 memory object is set to either the calling process's effective group ID
266 or "a system default group ID".
267 POSIX.1-2008 says that the group ownership
268 may be set to either the calling process's effective group ID
269 or, if the object is visible in the filesystem,
270 the group ID of the parent directory.
272 POSIX leaves the behavior of the combination of
277 On Linux, this will successfully truncate an existing
278 shared memory object\(emthis may not be so on other UNIX systems.
280 The POSIX shared memory object implementation on Linux makes use
283 filesystem that is normally mounted under
286 The programs below employ POSIX shared memory and POSIX unnamed semaphores
287 to exchange a piece of data.
288 The "bounce" program (which must be run first) raises the case
289 of a string that is placed into the shared memory by the "send" program.
290 Once the data has been modified, the "send" program then prints
291 the contents of the modified shared memory.
292 An example execution of the two programs is the following:
296 $ \fB./pshm_ucase_bounce /myshm &\fP
298 $ \fB./pshm_ucase_send /myshm hello\fP
303 Further detail about these programs is provided below.
305 .SS Program source: pshm_ucase.h
306 The following header file is included by both programs below.
307 Its primary purpose is to define a structure that will be imposed
308 on the memory object that is shared between the two programs.
312 #include <sys/mman.h>
314 #include <semaphore.h>
315 #include <sys/stat.h>
320 #define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \e
323 #define BUF_SIZE 1024 /* Maximum size for exchanged string */
325 /* Define a structure that will be imposed on the shared
329 sem_t sem1; /* POSIX unnamed semaphore */
330 sem_t sem2; /* POSIX unnamed semaphore */
331 size_t cnt; /* Number of bytes used in \(aqbuf\(aq */
332 char buf[BUF_SIZE]; /* Data being transferred */
337 .SS Program source: pshm_ucase_bounce.c
338 The "bounce" program creates a new shared memory object with the name
339 given in its command-line argument and sizes the object to
340 match the size of the
342 structure defined in the header file.
343 It then maps the object into the process's address space,
344 and initializes two POSIX semaphores inside the object to 0.
346 After the "send" program has posted the first of the semaphores,
347 the "bounce" program upper cases the data that has been placed
348 in the memory by the "send" program and then posts the second semaphore
349 to tell the "send" program that it may now access the shared memory.
353 /* pshm_ucase_bounce.c
355 Licensed under GNU General Public License v2 or later.
358 #include "pshm_ucase.h"
361 main(int argc, char *argv[])
364 fprintf(stderr, "Usage: %s /shm\-path\en", argv[0]);
368 char *shmpath = argv[1];
370 /* Create shared memory object and set its size to the size
373 int fd = shm_open(shmpath, O_CREAT | O_EXCL | O_RDWR,
378 if (ftruncate(fd, sizeof(struct shmbuf)) == \-1)
379 errExit("ftruncate");
381 /* Map the object into the caller\(aqs address space. */
383 struct shmbuf *shmp = mmap(NULL, sizeof(*shmp),
384 PROT_READ | PROT_WRITE,
386 if (shmp == MAP_FAILED)
389 /* Initialize semaphores as process\-shared, with value 0. */
391 if (sem_init(&shmp\->sem1, 1, 0) == \-1)
392 errExit("sem_init\-sem1");
393 if (sem_init(&shmp\->sem2, 1, 0) == \-1)
394 errExit("sem_init\-sem2");
396 /* Wait for \(aqsem1\(aq to be posted by peer before touching
399 if (sem_wait(&shmp\->sem1) == \-1)
402 /* Convert data in shared memory into upper case. */
404 for (int j = 0; j < shmp\->cnt; j++)
405 shmp\->buf[j] = toupper((unsigned char) shmp\->buf[j]);
407 /* Post \(aqsem2\(aq to tell the peer that it can now
408 access the modified data in shared memory. */
410 if (sem_post(&shmp\->sem2) == \-1)
413 /* Unlink the shared memory object. Even if the peer process
414 is still using the object, this is okay. The object will
415 be removed only after all open references are closed. */
424 .SS Program source: pshm_ucase_send.c
425 The "send" program takes two command-line arguments:
426 the pathname of a shared memory object previously created by the "bounce"
427 program and a string that is to be copied into that object.
429 The program opens the shared memory object
430 and maps the object into its address space.
431 It then copies the data specified in its second argument
432 into the shared memory,
433 and posts the first semaphore,
434 which tells the "bounce" program that it can now access that data.
435 After the "bounce" program posts the second semaphore,
436 the "send" program prints the contents of the shared memory
443 Licensed under GNU General Public License v2 or later.
446 #include "pshm_ucase.h"
449 main(int argc, char *argv[])
452 fprintf(stderr, "Usage: %s /shm\-path string\en", argv[0]);
456 char *shmpath = argv[1];
457 char *string = argv[2];
458 size_t len = strlen(string);
460 if (len > BUF_SIZE) {
461 fprintf(stderr, "String is too long\en");
465 /* Open the existing shared memory object and map it
466 into the caller\(aqs address space. */
468 int fd = shm_open(shmpath, O_RDWR, 0);
472 struct shmbuf *shmp = mmap(NULL, sizeof(*shmp),
473 PROT_READ | PROT_WRITE,
475 if (shmp == MAP_FAILED)
478 /* Copy data into the shared memory object. */
481 memcpy(&shmp\->buf, string, len);
483 /* Tell peer that it can now access shared memory. */
485 if (sem_post(&shmp\->sem1) == \-1)
488 /* Wait until peer says that it has finished accessing
489 the shared memory. */
491 if (sem_wait(&shmp\->sem2) == \-1)
494 /* Write modified data in shared memory to standard output. */
496 write(STDOUT_FILENO, &shmp\->buf, len);
497 write(STDOUT_FILENO, "\en", 1);
510 .BR memfd_create (2),