Changes: Ready for 5.13
[man-pages.git] / man3 / shm_open.3
blob265435e4e2ab9e8557b725d38a077f1fc501c30f
1 .\" Copyright (C) 2002, 2020 Michael Kerrisk <mtk.manpages@gmail.com>
2 .\"
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.
7 .\"
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.
12 .\"
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
19 .\" professionally.
20 .\"
21 .\" Formatted or processed versions of this manual, if unaccompanied by
22 .\" the source, must acknowledge the copyright and authors of this work.
23 .\" %%%LICENSE_END
24 .\"
25 .TH SHM_OPEN 3 2021-03-22 "Linux" "Linux Programmer's Manual"
26 .SH NAME
27 shm_open, shm_unlink \- create/open or unlink POSIX shared memory objects
28 .SH SYNOPSIS
29 .nf
30 .B #include <sys/mman.h>
31 .BR "#include <sys/stat.h>" "        /* For mode constants */"
32 .BR "#include <fcntl.h>" "           /* For O_* constants */"
33 .PP
34 .BI "int shm_open(const char *" name ", int " oflag ", mode_t " mode );
35 .BI "int shm_unlink(const char *" name );
36 .fi
37 .PP
38 Link with \fI\-lrt\fP.
39 .SH DESCRIPTION
40 .BR shm_open ()
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
44 .BR mmap (2)
45 the same region of shared memory.
46 The
47 .BR shm_unlink ()
48 function performs the converse operation,
49 removing an object previously created by
50 .BR shm_open ().
51 .PP
52 The operation of
53 .BR shm_open ()
54 is analogous to that of
55 .BR open (2).
56 .I name
57 specifies the shared memory object to be created or opened.
58 For portable use,
59 a shared memory object should be identified by a name of the form
60 .IR /somename ;
61 that is, a null-terminated string of up to
62 .BI NAME_MAX
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.
72 .PP
73 .I oflag
74 is a bit mask created by ORing together exactly one of
75 .B O_RDONLY
77 .B O_RDWR
78 and any of the other flags listed here:
79 .TP
80 .B O_RDONLY
81 Open the object for read access.
82 A shared memory object opened in this way can be
83 .BR mmap (2)ed
84 only for read
85 .RB ( PROT_READ )
86 access.
87 .TP
88 .B O_RDWR
89 Open the object for read-write access.
90 .TP
91 .B O_CREAT
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)
97 and the object's
98 permission bits are set according to the low-order 9 bits of
99 .IR mode ,
100 except that those bits set in the process file mode
101 creation mask (see
102 .BR umask (2))
103 are cleared for the new object.
104 A set of macro constants which can be used to define
105 .I mode
106 is listed in
107 .BR open (2).
108 (Symbolic definitions of these constants can be obtained by including
109 .IR <sys/stat.h> .)
111 A new shared memory object initially has zero length\(emthe size of the
112 object can be set using
113 .BR ftruncate (2).
114 The newly allocated bytes of a shared memory
115 object are automatically initialized to 0.
117 .B O_EXCL
119 .B O_CREAT
120 was also specified, and a shared memory object with the given
121 .I name
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.
126 .B O_TRUNC
127 If the shared memory object already exists, truncate it to zero bytes.
129 Definitions of these flag values can be obtained by including
130 .IR <fcntl.h> .
132 On successful completion
133 .BR shm_open ()
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.
138 .B FD_CLOEXEC
139 flag (see
140 .BR fcntl (2))
141 is set for the file descriptor.
143 The file descriptor is normally used in subsequent calls
145 .BR ftruncate (2)
146 (for a newly created object) and
147 .BR mmap (2).
148 After a call to
149 .BR mmap (2)
150 the file descriptor may be closed without affecting the memory mapping.
152 The operation
154 .BR shm_unlink ()
155 is analogous to
156 .BR unlink (2):
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.
160 After a successful
161 .BR shm_unlink (),
162 attempts to
163 .BR shm_open ()
164 an object with the same
165 .I name
166 fail (unless
167 .B O_CREAT
168 was specified, in which case a new, distinct object is created).
169 .SH RETURN VALUE
170 On success,
171 .BR shm_open ()
172 returns a file descriptor (a nonnegative integer).
173 On success,
174 .BR shm_unlink ()
175 returns 0.
176 On failure, both functions return \-1 and set
177 .I errno
178 to indicate the error.
179 .SH ERRORS
181 .B EACCES
182 Permission to
183 .BR shm_unlink ()
184 the shared memory object was denied.
186 .B EACCES
187 Permission was denied to
188 .BR shm_open ()
189 .I name
190 in the specified
191 .IR mode ,
193 .B O_TRUNC
194 was specified and the caller does not have write permission on the object.
196 .B EEXIST
197 Both
198 .B O_CREAT
200 .B O_EXCL
201 were specified to
202 .BR shm_open ()
203 and the shared memory object specified by
204 .I name
205 already exists.
207 .B EINVAL
209 .I name
210 argument to
211 .BR shm_open ()
212 was invalid.
214 .B EMFILE
215 The per-process limit on the number of open file descriptors has been reached.
217 .B ENAMETOOLONG
218 The length of
219 .I name
220 exceeds
221 .BR PATH_MAX .
223 .B ENFILE
224 The system-wide limit on the total number of open files has been reached.
226 .B ENOENT
227 An attempt was made to
228 .BR shm_open ()
230 .I name
231 that did not exist, and
232 .B O_CREAT
233 was not specified.
235 .B ENOENT
236 An attempt was to made to
237 .BR shm_unlink ()
239 .I name
240 that does not exist.
241 .SH VERSIONS
242 These functions are provided in glibc 2.2 and later.
243 .SH ATTRIBUTES
244 For an explanation of the terms used in this section, see
245 .BR attributes (7).
246 .ad l
249 allbox;
250 lbx lb lb
251 l l l.
252 Interface       Attribute       Value
254 .BR shm_open (),
255 .BR shm_unlink ()
256 T}      Thread safety   MT-Safe locale
260 .sp 1
261 .SH CONFORMING TO
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.
271 .SH NOTES
272 POSIX leaves the behavior of the combination of
273 .B O_RDONLY
275 .B O_TRUNC
276 unspecified.
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
281 of a dedicated
282 .BR tmpfs (5)
283 filesystem that is normally mounted under
284 .IR /dev/shm .
285 .SH EXAMPLES
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:
294 .in +4n
296 $ \fB./pshm_ucase_bounce /myshm &\fP
297 [1] 270171
298 $ \fB./pshm_ucase_send /myshm hello\fP
299 HELLO
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.
310 .in +4n
312 #include <sys/mman.h>
313 #include <fcntl.h>
314 #include <semaphore.h>
315 #include <sys/stat.h>
316 #include <stdio.h>
317 #include <stdlib.h>
318 #include <unistd.h>
320 #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \e
321                         } while (0)
323 #define BUF_SIZE 1024   /* Maximum size for exchanged string */
325 /* Define a structure that will be imposed on the shared
326    memory object */
328 struct shmbuf {
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
341 .I shmbuf
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.
351 .in +4n
353 /* pshm_ucase_bounce.c
355    Licensed under GNU General Public License v2 or later.
357 #include <ctype.h>
358 #include "pshm_ucase.h"
361 main(int argc, char *argv[])
363     if (argc != 2) {
364         fprintf(stderr, "Usage: %s /shm\-path\en", argv[0]);
365         exit(EXIT_FAILURE);
366     }
368     char *shmpath = argv[1];
370     /* Create shared memory object and set its size to the size
371        of our structure. */
373     int fd = shm_open(shmpath, O_CREAT | O_EXCL | O_RDWR,
374                       S_IRUSR | S_IWUSR);
375     if (fd == \-1)
376         errExit("shm_open");
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,
385                                MAP_SHARED, fd, 0);
386     if (shmp == MAP_FAILED)
387         errExit("mmap");
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
397        shared memory. */
399     if (sem_wait(&shmp\->sem1) == \-1)
400         errExit("sem_wait");
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)
411         errExit("sem_post");
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. */
417     shm_unlink(shmpath);
419     exit(EXIT_SUCCESS);
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
437 on standard output.
439 .in +4n
441 /* pshm_ucase_send.c
443    Licensed under GNU General Public License v2 or later.
445 #include <string.h>
446 #include "pshm_ucase.h"
449 main(int argc, char *argv[])
451     if (argc != 3) {
452         fprintf(stderr, "Usage: %s /shm\-path string\en", argv[0]);
453         exit(EXIT_FAILURE);
454     }
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");
462         exit(EXIT_FAILURE);
463     }
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);
469     if (fd == \-1)
470         errExit("shm_open");
472     struct shmbuf *shmp = mmap(NULL, sizeof(*shmp),
473                                PROT_READ | PROT_WRITE,
474                                MAP_SHARED, fd, 0);
475     if (shmp == MAP_FAILED)
476         errExit("mmap");
478     /* Copy data into the shared memory object. */
480     shmp\->cnt = len;
481     memcpy(&shmp\->buf, string, len);
483     /* Tell peer that it can now access shared memory. */
485     if (sem_post(&shmp\->sem1) == \-1)
486         errExit("sem_post");
488     /* Wait until peer says that it has finished accessing
489        the shared memory. */
491     if (sem_wait(&shmp\->sem2) == \-1)
492         errExit("sem_wait");
494     /* Write modified data in shared memory to standard output. */
496     write(STDOUT_FILENO, &shmp\->buf, len);
497     write(STDOUT_FILENO, "\en", 1);
499     exit(EXIT_SUCCESS);
503 .SH SEE ALSO
504 .BR close (2),
505 .BR fchmod (2),
506 .BR fchown (2),
507 .BR fcntl (2),
508 .BR fstat (2),
509 .BR ftruncate (2),
510 .BR memfd_create (2),
511 .BR mmap (2),
512 .BR open (2),
513 .BR umask (2),
514 .BR shm_overview (7)