1SHM_OPEN(3) Linux Programmer's Manual SHM_OPEN(3)
2
3
4
6 shm_open, shm_unlink - create/open or unlink POSIX shared memory ob‐
7 jects
8
10 #include <sys/mman.h>
11 #include <sys/stat.h> /* For mode constants */
12 #include <fcntl.h> /* For O_* constants */
13
14 int shm_open(const char *name, int oflag, mode_t mode);
15 int shm_unlink(const char *name);
16
17 Link with -lrt.
18
20 shm_open() creates and opens a new, or opens an existing, POSIX shared
21 memory object. A POSIX shared memory object is in effect a handle
22 which can be used by unrelated processes to mmap(2) the same region of
23 shared memory. The shm_unlink() function performs the converse opera‐
24 tion, removing an object previously created by shm_open().
25
26 The operation of shm_open() is analogous to that of open(2). name
27 specifies the shared memory object to be created or opened. For porta‐
28 ble use, a shared memory object should be identified by a name of the
29 form /somename; that is, a null-terminated string of up to NAME_MAX
30 (i.e., 255) characters consisting of an initial slash, followed by one
31 or more characters, none of which are slashes.
32
33 oflag is a bit mask created by ORing together exactly one of O_RDONLY
34 or O_RDWR and any of the other flags listed here:
35
36 O_RDONLY
37 Open the object for read access. A shared memory object opened
38 in this way can be mmap(2)ed only for read (PROT_READ) access.
39
40 O_RDWR Open the object for read-write access.
41
42 O_CREAT
43 Create the shared memory object if it does not exist. The user
44 and group ownership of the object are taken from the correspond‐
45 ing effective IDs of the calling process, and the object's per‐
46 mission bits are set according to the low-order 9 bits of mode,
47 except that those bits set in the process file mode creation
48 mask (see umask(2)) are cleared for the new object. A set of
49 macro constants which can be used to define mode is listed in
50 open(2). (Symbolic definitions of these constants can be ob‐
51 tained by including <sys/stat.h>.)
52
53 A new shared memory object initially has zero length—the size of
54 the object can be set using ftruncate(2). The newly allocated
55 bytes of a shared memory object are automatically initialized to
56 0.
57
58 O_EXCL If O_CREAT was also specified, and a shared memory object with
59 the given name already exists, return an error. The check for
60 the existence of the object, and its creation if it does not ex‐
61 ist, are performed atomically.
62
63 O_TRUNC
64 If the shared memory object already exists, truncate it to zero
65 bytes.
66
67 Definitions of these flag values can be obtained by including <fc‐
68 ntl.h>.
69
70 On successful completion shm_open() returns a new file descriptor re‐
71 ferring to the shared memory object. This file descriptor is guaran‐
72 teed to be the lowest-numbered file descriptor not previously opened
73 within the process. The FD_CLOEXEC flag (see fcntl(2)) is set for the
74 file descriptor.
75
76 The file descriptor is normally used in subsequent calls to ftrun‐
77 cate(2) (for a newly created object) and mmap(2). After a call to
78 mmap(2) the file descriptor may be closed without affecting the memory
79 mapping.
80
81 The operation of shm_unlink() is analogous to unlink(2): it removes a
82 shared memory object name, and, once all processes have unmapped the
83 object, deallocates and destroys the contents of the associated memory
84 region. After a successful shm_unlink(), attempts to shm_open() an ob‐
85 ject with the same name fail (unless O_CREAT was specified, in which
86 case a new, distinct object is created).
87
89 On success, shm_open() returns a file descriptor (a nonnegative inte‐
90 ger). On success, shm_unlink() returns 0. On failure, both functions
91 return -1 and set errno to indicate the error.
92
94 EACCES Permission to shm_unlink() the shared memory object was denied.
95
96 EACCES Permission was denied to shm_open() name in the specified mode,
97 or O_TRUNC was specified and the caller does not have write per‐
98 mission on the object.
99
100 EEXIST Both O_CREAT and O_EXCL were specified to shm_open() and the
101 shared memory object specified by name already exists.
102
103 EINVAL The name argument to shm_open() was invalid.
104
105 EMFILE The per-process limit on the number of open file descriptors has
106 been reached.
107
108 ENAMETOOLONG
109 The length of name exceeds PATH_MAX.
110
111 ENFILE The system-wide limit on the total number of open files has been
112 reached.
113
114 ENOENT An attempt was made to shm_open() a name that did not exist, and
115 O_CREAT was not specified.
116
117 ENOENT An attempt was to made to shm_unlink() a name that does not ex‐
118 ist.
119
121 These functions are provided in glibc 2.2 and later.
122
124 For an explanation of the terms used in this section, see at‐
125 tributes(7).
126
127 ┌─────────────────────────────────────┬───────────────┬────────────────┐
128 │Interface │ Attribute │ Value │
129 ├─────────────────────────────────────┼───────────────┼────────────────┤
130 │shm_open(), shm_unlink() │ Thread safety │ MT-Safe locale │
131 └─────────────────────────────────────┴───────────────┴────────────────┘
132
134 POSIX.1-2001, POSIX.1-2008.
135
136 POSIX.1-2001 says that the group ownership of a newly created shared
137 memory object is set to either the calling process's effective group ID
138 or "a system default group ID". POSIX.1-2008 says that the group own‐
139 ership may be set to either the calling process's effective group ID
140 or, if the object is visible in the filesystem, the group ID of the
141 parent directory.
142
144 POSIX leaves the behavior of the combination of O_RDONLY and O_TRUNC
145 unspecified. On Linux, this will successfully truncate an existing
146 shared memory object—this may not be so on other UNIX systems.
147
148 The POSIX shared memory object implementation on Linux makes use of a
149 dedicated tmpfs(5) filesystem that is normally mounted under /dev/shm.
150
152 The programs below employ POSIX shared memory and POSIX unnamed sema‐
153 phores to exchange a piece of data. The "bounce" program (which must
154 be run first) raises the case of a string that is placed into the
155 shared memory by the "send" program. Once the data has been modified,
156 the "send" program then prints the contents of the modified shared mem‐
157 ory. An example execution of the two programs is the following:
158
159 $ ./pshm_ucase_bounce /myshm &
160 [1] 270171
161 $ ./pshm_ucase_send /myshm hello
162 HELLO
163
164 Further detail about these programs is provided below.
165
166 Program source: pshm_ucase.h
167 The following header file is included by both programs below. Its pri‐
168 mary purpose is to define a structure that will be imposed on the mem‐
169 ory object that is shared between the two programs.
170
171 #include <sys/mman.h>
172 #include <fcntl.h>
173 #include <semaphore.h>
174 #include <sys/stat.h>
175 #include <stdio.h>
176 #include <stdlib.h>
177 #include <unistd.h>
178
179 #define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \
180 } while (0)
181
182 #define BUF_SIZE 1024 /* Maximum size for exchanged string */
183
184 /* Define a structure that will be imposed on the shared
185 memory object */
186
187 struct shmbuf {
188 sem_t sem1; /* POSIX unnamed semaphore */
189 sem_t sem2; /* POSIX unnamed semaphore */
190 size_t cnt; /* Number of bytes used in 'buf' */
191 char buf[BUF_SIZE]; /* Data being transferred */
192 };
193
194 Program source: pshm_ucase_bounce.c
195 The "bounce" program creates a new shared memory object with the name
196 given in its command-line argument and sizes the object to match the
197 size of the shmbuf structure defined in the header file. It then maps
198 the object into the process's address space, and initializes two POSIX
199 semaphores inside the object to 0.
200
201 After the "send" program has posted the first of the semaphores, the
202 "bounce" program upper cases the data that has been placed in the mem‐
203 ory by the "send" program and then posts the second semaphore to tell
204 the "send" program that it may now access the shared memory.
205
206 /* pshm_ucase_bounce.c
207
208 Licensed under GNU General Public License v2 or later.
209 */
210 #include <ctype.h>
211 #include "pshm_ucase.h"
212
213 int
214 main(int argc, char *argv[])
215 {
216 if (argc != 2) {
217 fprintf(stderr, "Usage: %s /shm-path\n", argv[0]);
218 exit(EXIT_FAILURE);
219 }
220
221 char *shmpath = argv[1];
222
223 /* Create shared memory object and set its size to the size
224 of our structure. */
225
226 int fd = shm_open(shmpath, O_CREAT | O_EXCL | O_RDWR,
227 S_IRUSR | S_IWUSR);
228 if (fd == -1)
229 errExit("shm_open");
230
231 if (ftruncate(fd, sizeof(struct shmbuf)) == -1)
232 errExit("ftruncate");
233
234 /* Map the object into the caller's address space. */
235
236 struct shmbuf *shmp = mmap(NULL, sizeof(*shmp),
237 PROT_READ | PROT_WRITE,
238 MAP_SHARED, fd, 0);
239 if (shmp == MAP_FAILED)
240 errExit("mmap");
241
242 /* Initialize semaphores as process-shared, with value 0. */
243
244 if (sem_init(&shmp->sem1, 1, 0) == -1)
245 errExit("sem_init-sem1");
246 if (sem_init(&shmp->sem2, 1, 0) == -1)
247 errExit("sem_init-sem2");
248
249 /* Wait for 'sem1' to be posted by peer before touching
250 shared memory. */
251
252 if (sem_wait(&shmp->sem1) == -1)
253 errExit("sem_wait");
254
255 /* Convert data in shared memory into upper case. */
256
257 for (int j = 0; j < shmp->cnt; j++)
258 shmp->buf[j] = toupper((unsigned char) shmp->buf[j]);
259
260 /* Post 'sem2' to tell the peer that it can now
261 access the modified data in shared memory. */
262
263 if (sem_post(&shmp->sem2) == -1)
264 errExit("sem_post");
265
266 /* Unlink the shared memory object. Even if the peer process
267 is still using the object, this is okay. The object will
268 be removed only after all open references are closed. */
269
270 shm_unlink(shmpath);
271
272 exit(EXIT_SUCCESS);
273 }
274
275 Program source: pshm_ucase_send.c
276 The "send" program takes two command-line arguments: the pathname of a
277 shared memory object previously created by the "bounce" program and a
278 string that is to be copied into that object.
279
280 The program opens the shared memory object and maps the object into its
281 address space. It then copies the data specified in its second argu‐
282 ment into the shared memory, and posts the first semaphore, which tells
283 the "bounce" program that it can now access that data. After the
284 "bounce" program posts the second semaphore, the "send" program prints
285 the contents of the shared memory on standard output.
286
287 /* pshm_ucase_send.c
288
289 Licensed under GNU General Public License v2 or later.
290 */
291 #include <string.h>
292 #include "pshm_ucase.h"
293
294 int
295 main(int argc, char *argv[])
296 {
297 if (argc != 3) {
298 fprintf(stderr, "Usage: %s /shm-path string\n", argv[0]);
299 exit(EXIT_FAILURE);
300 }
301
302 char *shmpath = argv[1];
303 char *string = argv[2];
304 size_t len = strlen(string);
305
306 if (len > BUF_SIZE) {
307 fprintf(stderr, "String is too long\n");
308 exit(EXIT_FAILURE);
309 }
310
311 /* Open the existing shared memory object and map it
312 into the caller's address space. */
313
314 int fd = shm_open(shmpath, O_RDWR, 0);
315 if (fd == -1)
316 errExit("shm_open");
317
318 struct shmbuf *shmp = mmap(NULL, sizeof(*shmp),
319 PROT_READ | PROT_WRITE,
320 MAP_SHARED, fd, 0);
321 if (shmp == MAP_FAILED)
322 errExit("mmap");
323
324 /* Copy data into the shared memory object. */
325
326 shmp->cnt = len;
327 memcpy(&shmp->buf, string, len);
328
329 /* Tell peer that it can now access shared memory. */
330
331 if (sem_post(&shmp->sem1) == -1)
332 errExit("sem_post");
333
334 /* Wait until peer says that it has finished accessing
335 the shared memory. */
336
337 if (sem_wait(&shmp->sem2) == -1)
338 errExit("sem_wait");
339
340 /* Write modified data in shared memory to standard output. */
341
342 write(STDOUT_FILENO, &shmp->buf, len);
343 write(STDOUT_FILENO, "\n", 1);
344
345 exit(EXIT_SUCCESS);
346 }
347
349 close(2), fchmod(2), fchown(2), fcntl(2), fstat(2), ftruncate(2),
350 memfd_create(2), mmap(2), open(2), umask(2), shm_overview(7)
351
353 This page is part of release 5.12 of the Linux man-pages project. A
354 description of the project, information about reporting bugs, and the
355 latest version of this page, can be found at
356 https://www.kernel.org/doc/man-pages/.
357
358
359
360Linux 2021-03-22 SHM_OPEN(3)