tzfile.5, tzselect.8: sync from tzdb upstream
[man-pages.git] / man3 / shm_open.3
blob16bf212b21324b5a8f22d28dd3144a6942044c17
1 '\" t
2 .\" Copyright (C) 2002, 2020 Michael Kerrisk <mtk.manpages@gmail.com>
3 .\"
4 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
5 .\"
6 .TH shm_open 3 (date) "Linux man-pages (unreleased)"
7 .SH NAME
8 shm_open, shm_unlink \- create/open or unlink POSIX shared memory objects
9 .SH LIBRARY
10 Real-time library
11 .RI ( librt ", " \-lrt )
12 .SH SYNOPSIS
13 .nf
14 .B #include <sys/mman.h>
15 .BR "#include <sys/stat.h>" "        /* For mode constants */"
16 .BR "#include <fcntl.h>" "           /* For O_* constants */"
17 .PP
18 .BI "int shm_open(const char *" name ", int " oflag ", mode_t " mode );
19 .BI "int shm_unlink(const char *" name );
20 .fi
21 .SH DESCRIPTION
22 .BR shm_open ()
23 creates and opens a new, or opens an existing, POSIX shared memory object.
24 A POSIX shared memory object is in effect a handle which can
25 be used by unrelated processes to
26 .BR mmap (2)
27 the same region of shared memory.
28 The
29 .BR shm_unlink ()
30 function performs the converse operation,
31 removing an object previously created by
32 .BR shm_open ().
33 .PP
34 The operation of
35 .BR shm_open ()
36 is analogous to that of
37 .BR open (2).
38 .I name
39 specifies the shared memory object to be created or opened.
40 For portable use,
41 a shared memory object should be identified by a name of the form
42 .IR /somename ;
43 that is, a null-terminated string of up to
44 .B NAME_MAX
45 (i.e., 255) characters consisting of an initial slash,
46 .\" glibc allows the initial slash to be omitted, and makes
47 .\" multiple initial slashes equivalent to a single slash.
48 .\" This differs from the implementation of POSIX message queues.
49 followed by one or more characters, none of which are slashes.
50 .\" glibc allows subdirectory components in the name, in which
51 .\" case the subdirectory must exist under /dev/shm, and allow the
52 .\" required permissions if a user wants to create a shared memory
53 .\" object in that subdirectory.
54 .PP
55 .I oflag
56 is a bit mask created by ORing together exactly one of
57 .B O_RDONLY
59 .B O_RDWR
60 and any of the other flags listed here:
61 .TP
62 .B O_RDONLY
63 Open the object for read access.
64 A shared memory object opened in this way can be
65 .BR mmap (2)ed
66 only for read
67 .RB ( PROT_READ )
68 access.
69 .TP
70 .B O_RDWR
71 Open the object for read-write access.
72 .TP
73 .B O_CREAT
74 Create the shared memory object if it does not exist.
75 The user and group ownership of the object are taken
76 from the corresponding effective IDs of the calling process,
77 .\" In truth it is actually the filesystem IDs on Linux, but these
78 .\" are nearly always the same as the effective IDs.  (MTK, Jul 05)
79 and the object's
80 permission bits are set according to the low-order 9 bits of
81 .IR mode ,
82 except that those bits set in the process file mode
83 creation mask (see
84 .BR umask (2))
85 are cleared for the new object.
86 A set of macro constants which can be used to define
87 .I mode
88 is listed in
89 .BR open (2).
90 (Symbolic definitions of these constants can be obtained by including
91 .IR <sys/stat.h> .)
92 .IP
93 A new shared memory object initially has zero length\[em]the size of the
94 object can be set using
95 .BR ftruncate (2).
96 The newly allocated bytes of a shared memory
97 object are automatically initialized to 0.
98 .TP
99 .B O_EXCL
101 .B O_CREAT
102 was also specified, and a shared memory object with the given
103 .I name
104 already exists, return an error.
105 The check for the existence of the object, and its creation if it
106 does not exist, are performed atomically.
108 .B O_TRUNC
109 If the shared memory object already exists, truncate it to zero bytes.
111 Definitions of these flag values can be obtained by including
112 .IR <fcntl.h> .
114 On successful completion
115 .BR shm_open ()
116 returns a new file descriptor referring to the shared memory object.
117 This file descriptor is guaranteed to be the lowest-numbered file descriptor
118 not previously opened within the process.
120 .B FD_CLOEXEC
121 flag (see
122 .BR fcntl (2))
123 is set for the file descriptor.
125 The file descriptor is normally used in subsequent calls
127 .BR ftruncate (2)
128 (for a newly created object) and
129 .BR mmap (2).
130 After a call to
131 .BR mmap (2)
132 the file descriptor may be closed without affecting the memory mapping.
134 The operation
136 .BR shm_unlink ()
137 is analogous to
138 .BR unlink (2):
139 it removes a shared memory object name, and, once all processes
140 have unmapped the object, deallocates and
141 destroys the contents of the associated memory region.
142 After a successful
143 .BR shm_unlink (),
144 attempts to
145 .BR shm_open ()
146 an object with the same
147 .I name
148 fail (unless
149 .B O_CREAT
150 was specified, in which case a new, distinct object is created).
151 .SH RETURN VALUE
152 On success,
153 .BR shm_open ()
154 returns a file descriptor (a nonnegative integer).
155 On success,
156 .BR shm_unlink ()
157 returns 0.
158 On failure, both functions return \-1 and set
159 .I errno
160 to indicate the error.
161 .SH ERRORS
163 .B EACCES
164 Permission to
165 .BR shm_unlink ()
166 the shared memory object was denied.
168 .B EACCES
169 Permission was denied to
170 .BR shm_open ()
171 .I name
172 in the specified
173 .IR mode ,
175 .B O_TRUNC
176 was specified and the caller does not have write permission on the object.
178 .B EEXIST
179 Both
180 .B O_CREAT
182 .B O_EXCL
183 were specified to
184 .BR shm_open ()
185 and the shared memory object specified by
186 .I name
187 already exists.
189 .B EINVAL
191 .I name
192 argument to
193 .BR shm_open ()
194 was invalid.
196 .B EMFILE
197 The per-process limit on the number of open file descriptors has been reached.
199 .B ENAMETOOLONG
200 The length of
201 .I name
202 exceeds
203 .BR PATH_MAX .
205 .B ENFILE
206 The system-wide limit on the total number of open files has been reached.
208 .B ENOENT
209 An attempt was made to
210 .BR shm_open ()
212 .I name
213 that did not exist, and
214 .B O_CREAT
215 was not specified.
217 .B ENOENT
218 An attempt was to made to
219 .BR shm_unlink ()
221 .I name
222 that does not exist.
223 .SH VERSIONS
224 These functions are provided in glibc 2.2 and later.
225 .SH ATTRIBUTES
226 For an explanation of the terms used in this section, see
227 .BR attributes (7).
228 .ad l
231 allbox;
232 lbx lb lb
233 l l l.
234 Interface       Attribute       Value
236 .BR shm_open (),
237 .BR shm_unlink ()
238 T}      Thread safety   MT-Safe locale
242 .sp 1
243 .SH STANDARDS
244 POSIX.1-2001, POSIX.1-2008.
246 POSIX.1-2001 says that the group ownership of a newly created shared
247 memory object is set to either the calling process's effective group ID
248 or "a system default group ID".
249 POSIX.1-2008 says that the group ownership
250 may be set to either the calling process's effective group ID
251 or, if the object is visible in the filesystem,
252 the group ID of the parent directory.
253 .SH NOTES
254 POSIX leaves the behavior of the combination of
255 .B O_RDONLY
257 .B O_TRUNC
258 unspecified.
259 On Linux, this will successfully truncate an existing
260 shared memory object\[em]this may not be so on other UNIX systems.
262 The POSIX shared memory object implementation on Linux makes use
263 of a dedicated
264 .BR tmpfs (5)
265 filesystem that is normally mounted under
266 .IR /dev/shm .
267 .SH EXAMPLES
268 The programs below employ POSIX shared memory and POSIX unnamed semaphores
269 to exchange a piece of data.
270 The "bounce" program (which must be run first) raises the case
271 of a string that is placed into the shared memory by the "send" program.
272 Once the data has been modified, the "send" program then prints
273 the contents of the modified shared memory.
274 An example execution of the two programs is the following:
276 .in +4n
278 $ \fB./pshm_ucase_bounce /myshm &\fP
279 [1] 270171
280 $ \fB./pshm_ucase_send /myshm hello\fP
281 HELLO
285 Further detail about these programs is provided below.
287 .SS Program source: pshm_ucase.h
288 The following header file is included by both programs below.
289 Its primary purpose is to define a structure that will be imposed
290 on the memory object that is shared between the two programs.
292 .in +4n
293 .\" SRC BEGIN (pshm_ucase.h)
295 #include <fcntl.h>
296 #include <semaphore.h>
297 #include <stdio.h>
298 #include <stdlib.h>
299 #include <sys/mman.h>
300 #include <sys/stat.h>
301 #include <unistd.h>
303 #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \e
304                         } while (0)
306 #define BUF_SIZE 1024   /* Maximum size for exchanged string */
308 /* Define a structure that will be imposed on the shared
309    memory object */
311 struct shmbuf {
312     sem_t  sem1;            /* POSIX unnamed semaphore */
313     sem_t  sem2;            /* POSIX unnamed semaphore */
314     size_t cnt;             /* Number of bytes used in \[aq]buf\[aq] */
315     char   buf[BUF_SIZE];   /* Data being transferred */
318 .\" SRC END
321 .SS Program source: pshm_ucase_bounce.c
322 The "bounce" program creates a new shared memory object with the name
323 given in its command-line argument and sizes the object to
324 match the size of the
325 .I shmbuf
326 structure defined in the header file.
327 It then maps the object into the process's address space,
328 and initializes two POSIX semaphores inside the object to 0.
330 After the "send" program has posted the first of the semaphores,
331 the "bounce" program upper cases the data that has been placed
332 in the memory by the "send" program and then posts the second semaphore
333 to tell the "send" program that it may now access the shared memory.
335 .in +4n
336 .\" SRC BEGIN (pshm_ucase_bounce.c)
338 /* pshm_ucase_bounce.c
340    Licensed under GNU General Public License v2 or later.
342 #include <ctype.h>
344 #include "pshm_ucase.h"
347 main(int argc, char *argv[])
349     int            fd;
350     char           *shmpath;
351     struct shmbuf  *shmp;
353     if (argc != 2) {
354         fprintf(stderr, "Usage: %s /shm\-path\en", argv[0]);
355         exit(EXIT_FAILURE);
356     }
358     shmpath = argv[1];
360     /* Create shared memory object and set its size to the size
361        of our structure. */
363     fd = shm_open(shmpath, O_CREAT | O_EXCL | O_RDWR, 0600);
364     if (fd == \-1)
365         errExit("shm_open");
367     if (ftruncate(fd, sizeof(struct shmbuf)) == \-1)
368         errExit("ftruncate");
370     /* Map the object into the caller\[aq]s address space. */
372     shmp = mmap(NULL, sizeof(*shmp), PROT_READ | PROT_WRITE,
373                 MAP_SHARED, fd, 0);
374     if (shmp == MAP_FAILED)
375         errExit("mmap");
377     /* Initialize semaphores as process\-shared, with value 0. */
379     if (sem_init(&shmp\->sem1, 1, 0) == \-1)
380         errExit("sem_init\-sem1");
381     if (sem_init(&shmp\->sem2, 1, 0) == \-1)
382         errExit("sem_init\-sem2");
384     /* Wait for \[aq]sem1\[aq] to be posted by peer before touching
385        shared memory. */
387     if (sem_wait(&shmp\->sem1) == \-1)
388         errExit("sem_wait");
390     /* Convert data in shared memory into upper case. */
392     for (size_t j = 0; j < shmp\->cnt; j++)
393         shmp\->buf[j] = toupper((unsigned char) shmp\->buf[j]);
395     /* Post \[aq]sem2\[aq] to tell the peer that it can now
396        access the modified data in shared memory. */
398     if (sem_post(&shmp\->sem2) == \-1)
399         errExit("sem_post");
401     /* Unlink the shared memory object. Even if the peer process
402        is still using the object, this is okay. The object will
403        be removed only after all open references are closed. */
405     shm_unlink(shmpath);
407     exit(EXIT_SUCCESS);
410 .\" SRC END
413 .SS Program source: pshm_ucase_send.c
414 The "send" program takes two command-line arguments:
415 the pathname of a shared memory object previously created by the "bounce"
416 program and a string that is to be copied into that object.
418 The program opens the shared memory object
419 and maps the object into its address space.
420 It then copies the data specified in its second argument
421 into the shared memory,
422 and posts the first semaphore,
423 which tells the "bounce" program that it can now access that data.
424 After the "bounce" program posts the second semaphore,
425 the "send" program prints the contents of the shared memory
426 on standard output.
428 .in +4n
429 .\" SRC BEGIN (pshm_ucase_send.c)
431 /* pshm_ucase_send.c
433    Licensed under GNU General Public License v2 or later.
435 #include <string.h>
437 #include "pshm_ucase.h"
440 main(int argc, char *argv[])
442     int            fd;
443     char           *shmpath, *string;
444     size_t         len;
445     struct shmbuf  *shmp;
447     if (argc != 3) {
448         fprintf(stderr, "Usage: %s /shm\-path string\en", argv[0]);
449         exit(EXIT_FAILURE);
450     }
452     shmpath = argv[1];
453     string = argv[2];
454     len = strlen(string);
456     if (len > BUF_SIZE) {
457         fprintf(stderr, "String is too long\en");
458         exit(EXIT_FAILURE);
459     }
461     /* Open the existing shared memory object and map it
462        into the caller\[aq]s address space. */
464     fd = shm_open(shmpath, O_RDWR, 0);
465     if (fd == \-1)
466         errExit("shm_open");
468     shmp = mmap(NULL, sizeof(*shmp), PROT_READ | PROT_WRITE,
469                 MAP_SHARED, fd, 0);
470     if (shmp == MAP_FAILED)
471         errExit("mmap");
473     /* Copy data into the shared memory object. */
475     shmp\->cnt = len;
476     memcpy(&shmp\->buf, string, len);
478     /* Tell peer that it can now access shared memory. */
480     if (sem_post(&shmp\->sem1) == \-1)
481         errExit("sem_post");
483     /* Wait until peer says that it has finished accessing
484        the shared memory. */
486     if (sem_wait(&shmp\->sem2) == \-1)
487         errExit("sem_wait");
489     /* Write modified data in shared memory to standard output. */
491     write(STDOUT_FILENO, &shmp\->buf, len);
492     write(STDOUT_FILENO, "\en", 1);
494     exit(EXIT_SUCCESS);
497 .\" SRC END
499 .SH SEE ALSO
500 .BR close (2),
501 .BR fchmod (2),
502 .BR fchown (2),
503 .BR fcntl (2),
504 .BR fstat (2),
505 .BR ftruncate (2),
506 .BR memfd_create (2),
507 .BR mmap (2),
508 .BR open (2),
509 .BR umask (2),
510 .BR shm_overview (7)