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