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 2020-04-11 "Linux" "Linux Programmer's Manual"
27 shm_open, shm_unlink \- create/open or unlink POSIX shared memory objects
29 .B #include <sys/mman.h>
31 .BR "#include <sys/stat.h>" " /* For mode constants */"
33 .BR "#include <fcntl.h>" " /* For O_* constants */"
35 .BI "int shm_open(const char *" name ", int " oflag ", mode_t " mode );
37 .BI "int shm_unlink(const char *" name );
39 Link with \fI\-lrt\fP.
42 creates and opens a new, or opens an existing, POSIX shared memory object.
43 A POSIX shared memory object is in effect a handle which can
44 be used by unrelated processes to
46 the same region of shared memory.
49 function performs the converse operation,
50 removing an object previously created by
55 is analogous to that of
58 specifies the shared memory object to be created or opened.
60 a shared memory object should be identified by a name of the form
62 that is, a null-terminated string of up to
64 (i.e., 255) characters consisting of an initial slash,
65 .\" glibc allows the initial slash to be omitted, and makes
66 .\" multiple initial slashes equivalent to a single slash.
67 .\" This differs from the implementation of POSIX message queues.
68 followed by one or more characters, none of which are slashes.
69 .\" glibc allows subdirectory components in the name, in which
70 .\" case the subdirectory must exist under /dev/shm, and allow the
71 .\" required permissions if a user wants to create a shared memory
72 .\" object in that subdirectory.
75 is a bit mask created by ORing together exactly one of
79 and any of the other flags listed here:
82 Open the object for read access.
83 A shared memory object opened in this way can be
90 Open the object for read-write access.
93 Create the shared memory object if it does not exist.
94 The user and group ownership of the object are taken
95 from the corresponding effective IDs of the calling process,
96 .\" In truth it is actually the filesystem IDs on Linux, but these
97 .\" are nearly always the same as the effective IDs. (MTK, Jul 05)
99 permission bits are set according to the low-order 9 bits of
101 except that those bits set in the process file mode
104 are cleared for the new object.
105 A set of macro constants which can be used to define
109 (Symbolic definitions of these constants can be obtained by including
112 A new shared memory object initially has zero length\(emthe size of the
113 object can be set using
115 The newly allocated bytes of a shared memory
116 object are automatically initialized to 0.
121 was also specified, and a shared memory object with the given
123 already exists, return an error.
124 The check for the existence of the object, and its creation if it
125 does not exist, are performed atomically.
128 If the shared memory object already exists, truncate it to zero bytes.
130 Definitions of these flag values can be obtained by including
133 On successful completion
135 returns a new file descriptor referring to the shared memory object.
136 This file descriptor is guaranteed to be the lowest-numbered file descriptor
137 not previously opened within the process.
142 is set for the file descriptor.
144 The file descriptor is normally used in subsequent calls
147 (for a newly created object) and
151 the file descriptor may be closed without affecting the memory mapping.
158 it removes a shared memory object name, and, once all processes
159 have unmapped the object, de-allocates and
160 destroys the contents of the associated memory region.
165 an object with the same
169 was specified, in which case a new, distinct object is created).
173 returns a file descriptor (a nonnegative integer).
178 returns 0 on success, or \-1 on error.
182 is set to indicate the cause of the error.
183 Values which may appear in
185 include the following:
190 the shared memory object was denied.
193 Permission was denied to
200 was specified and the caller does not have write permission on the object.
209 and the shared memory object specified by
221 The per-process limit on the number of open file descriptors has been reached.
230 The system-wide limit on the total number of open files has been reached.
233 An attempt was made to
237 that did not exist, and
242 An attempt was to made to
248 These functions are provided in glibc 2.2 and later.
250 For an explanation of the terms used in this section, see
256 Interface Attribute Value
260 T} Thread safety MT-Safe locale
264 POSIX.1-2001, POSIX.1-2008.
266 POSIX.1-2001 says that the group ownership of a newly created shared
267 memory object is set to either the calling process's effective group ID
268 or "a system default group ID".
269 POSIX.1-2008 says that the group ownership
270 may be set to either the calling process's effective group ID
271 or, if the object is visible in the filesystem,
272 the group ID of the parent directory.
275 POSIX leaves the behavior of the combination of
280 On Linux, this will successfully truncate an existing
281 shared memory object\(emthis may not be so on other UNIX systems.
283 The POSIX shared memory object implementation on Linux makes use
286 filesystem that is normally mounted under
289 The programs below employ POSIX shared memory and POSIX unnamed semaphores
290 to exchange a piece of data.
291 The "bounce" program (which must be run first) raises the case
292 of a string that is placed into the shared memory by the "send" program.
293 Once the data has been modified, the "send" program then prints
294 the contents of the modified shared memory.
295 An example execution of the two programs is the following:
299 $ \fB./pshm_ucase_bounce /myshm &\fP
301 $ \fB./pshm_ucase_send /myshm hello\fP
306 Further detail about these programs is provided below.
308 .SS Program source: pshm_ucase.h
309 The following header file is included by both programs below.
310 Its primary purpose is to define a structure that will be imposed
311 on the memory object that is shared between the two programs.
315 #include <sys/mman.h>
317 #include <semaphore.h>
318 #include <sys/stat.h>
323 #define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \e
326 #define BUF_SIZE 1024 /* Maximum size for exchanged string */
328 /* Define a structure that will be imposed on the shared
332 sem_t sem1; /* POSIX unnamed semaphore */
333 sem_t sem2; /* POSIX unnamed semaphore */
334 size_t cnt; /* Number of bytes used in \(aqbuf\(aq */
335 char buf[BUF_SIZE]; /* Data being transferred */
341 .SS Program source: pshm_ucase_bounce.c
343 The "bounce" program creates a new shared memory object with the name
344 given in its command-line argument and sizes the object to
345 match the size of the
347 structure defined in the header file.
348 It then maps the object into the process's address space,
349 and initializes two POSIX semaphores inside the object to 0.
351 After the "send" program has posted the first of the semaphores,
352 the "bounce" program upper cases the data that has been placed
353 in the memory by the "send" program and then posts the second semaphore
354 to tell the "send" program that it may now access the shared memory.
358 /* pshm_ucase_bounce.c
360 Licensed under GNU General Public License v2 or later.
363 #include "pshm_ucase.h"
366 main(int argc, char *argv[])
369 fprintf(stderr, "Usage: %s /shm\-path\en", argv[0]);
373 char *shmpath = argv[1];
375 /* Create shared memory object and set its size to the size
378 int fd = shm_open(shmpath, O_CREAT | O_EXCL | O_RDWR,
383 if (ftruncate(fd, sizeof(struct shmbuf)) == \-1)
384 errExit("ftruncate");
386 /* Map the object into the caller\(aqs address space */
388 struct shmbuf *shmp = mmap(NULL, sizeof(struct shmbuf),
389 PROT_READ | PROT_WRITE,
391 if (shmp == MAP_FAILED)
394 /* Initialize semaphores as process-shared, with value 0 */
396 if (sem_init(&shmp\->sem1, 1, 0) == \-1)
397 errExit("sem_init\-sem1");
398 if (sem_init(&shmp\->sem2, 1, 0) == \-1)
399 errExit("sem_init\-sem2");
401 /* Wait for \(aqsem1\(aq to be posted by peer before touching
404 if (sem_wait(&shmp\->sem1) == \-1)
407 /* Convert data in shared memory into upper case */
409 for (int j = 0; j < shmp\->cnt; j++)
410 shmp\->buf[j] = toupper((unsigned char) shmp\->buf[j]);
412 /* Post \(aqsem2\(aq to tell the to tell peer that it can now
413 access the modified data in shared memory */
415 if (sem_post(&shmp\->sem2) == \-1)
418 /* Unlink the shared memory object. Even if the peer process
419 is still using the object, this is okay. The object will
420 be removed only after all open references are closed. */
430 .SS Program source: pshm_ucase_send.c
432 The "send" program takes two command-line arguments:
433 the pathname of a shared memory object previously created by the "bounce"
434 program and a string that is to be copied into that object.
436 The program opens the shared memory object
437 and maps the object into its address space.
438 It then copies the data specified in its second argument
439 into the shared memory,
440 and posts the first semaphore,
441 which tells the "bounce" program that it can now access that data.
442 After the "bounce" program posts the second semaphore,
443 the "send" program prints the contents of the shared memory
450 Licensed under GNU General Public License v2 or later.
453 #include "pshm_ucase.h"
456 main(int argc, char *argv[])
459 fprintf(stderr, "Usage: %s /shm\-path string\en", argv[0]);
463 char *shmpath = argv[1];
464 char *string = argv[2];
465 size_t len = strlen(string);
467 if (len > BUF_SIZE) {
468 fprintf(stderr, "String is too long\en");
472 /* Open the existing shared memory object and map it
473 into the caller\(aqs address space */
475 int fd = shm_open(shmpath, O_RDWR, 0);
479 struct shmbuf *shmp = mmap(NULL, sizeof(struct shmbuf),
480 PROT_READ | PROT_WRITE,
482 if (shmp == MAP_FAILED)
485 /* Copy data into the shared memory object */
488 memcpy(&shmp\->buf, string, len);
490 /* Tell peer that it can now access shared memory */
492 if (sem_post(&shmp\->sem1) == \-1)
495 /* Wait until peer says that it has finished accessing
498 if (sem_wait(&shmp\->sem2) == \-1)
501 /* Write modified data in shared memory to standard output */
503 write(STDOUT_FILENO, &shmp\->buf, len);
504 write(STDOUT_FILENO, "\en", 1);
518 .BR memfd_create (2),