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
16 int shm_unlink(const char *name);
17
18 Link with -lrt.
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, de-allocates 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 failure, shm_open() returns -1. shm_unlink() returns 0 on
92 success, or -1 on error.
93
95 On failure, errno is set to indicate the cause of the error. Values
96 which may appear in errno include the following:
97
98 EACCES Permission to shm_unlink() the shared memory object was denied.
99
100 EACCES Permission was denied to shm_open() name in the specified mode,
101 or O_TRUNC was specified and the caller does not have write per‐
102 mission on the object.
103
104 EEXIST Both O_CREAT and O_EXCL were specified to shm_open() and the
105 shared memory object specified by name already exists.
106
107 EINVAL The name argument to shm_open() was invalid.
108
109 EMFILE The per-process limit on the number of open file descriptors has
110 been reached.
111
112 ENAMETOOLONG
113 The length of name exceeds PATH_MAX.
114
115 ENFILE The system-wide limit on the total number of open files has been
116 reached.
117
118 ENOENT An attempt was made to shm_open() a name that did not exist, and
119 O_CREAT was not specified.
120
121 ENOENT An attempt was to made to shm_unlink() a name that does not ex‐
122 ist.
123
125 These functions are provided in glibc 2.2 and later.
126
128 For an explanation of the terms used in this section, see at‐
129 tributes(7).
130
131 ┌─────────────────────────┬───────────────┬────────────────┐
132 │Interface │ Attribute │ Value │
133 ├─────────────────────────┼───────────────┼────────────────┤
134 │shm_open(), shm_unlink() │ Thread safety │ MT-Safe locale │
135 └─────────────────────────┴───────────────┴────────────────┘
136
138 POSIX.1-2001, POSIX.1-2008.
139
140 POSIX.1-2001 says that the group ownership of a newly created shared
141 memory object is set to either the calling process's effective group ID
142 or "a system default group ID". POSIX.1-2008 says that the group own‐
143 ership may be set to either the calling process's effective group ID
144 or, if the object is visible in the filesystem, the group ID of the
145 parent directory.
146
148 POSIX leaves the behavior of the combination of O_RDONLY and O_TRUNC
149 unspecified. On Linux, this will successfully truncate an existing
150 shared memory object—this may not be so on other UNIX systems.
151
152 The POSIX shared memory object implementation on Linux makes use of a
153 dedicated tmpfs(5) filesystem that is normally mounted under /dev/shm.
154
156 The programs below employ POSIX shared memory and POSIX unnamed sema‐
157 phores to exchange a piece of data. The "bounce" program (which must
158 be run first) raises the case of a string that is placed into the
159 shared memory by the "send" program. Once the data has been modified,
160 the "send" program then prints the contents of the modified shared mem‐
161 ory. An example execution of the two programs is the following:
162
163 $ ./pshm_ucase_bounce /myshm &
164 [1] 270171
165 $ ./pshm_ucase_send /myshm hello
166 HELLO
167
168 Further detail about these programs is provided below.
169
170 Program source: pshm_ucase.h
171 The following header file is included by both programs below. Its pri‐
172 mary purpose is to define a structure that will be imposed on the mem‐
173 ory object that is shared between the two programs.
174
175 #include <sys/mman.h>
176 #include <fcntl.h>
177 #include <semaphore.h>
178 #include <sys/stat.h>
179 #include <stdio.h>
180 #include <stdlib.h>
181 #include <unistd.h>
182
183 #define errExit(msg) do { perror(msg); exit(EXIT_FAILURE); \
184 } while (0)
185
186 #define BUF_SIZE 1024 /* Maximum size for exchanged string */
187
188 /* Define a structure that will be imposed on the shared
189 memory object */
190
191 struct shmbuf {
192 sem_t sem1; /* POSIX unnamed semaphore */
193 sem_t sem2; /* POSIX unnamed semaphore */
194 size_t cnt; /* Number of bytes used in 'buf' */
195 char buf[BUF_SIZE]; /* Data being transferred */
196 };
197
198 Program source: pshm_ucase_bounce.c
199 The "bounce" program creates a new shared memory object with the name
200 given in its command-line argument and sizes the object to match the
201 size of the shmbuf structure defined in the header file. It then maps
202 the object into the process's address space, and initializes two POSIX
203 semaphores inside the object to 0.
204
205 After the "send" program has posted the first of the semaphores, the
206 "bounce" program upper cases the data that has been placed in the mem‐
207 ory by the "send" program and then posts the second semaphore to tell
208 the "send" program that it may now access the shared memory.
209
210 /* pshm_ucase_bounce.c
211
212 Licensed under GNU General Public License v2 or later.
213 */
214 #include <ctype.h>
215 #include "pshm_ucase.h"
216
217 int
218 main(int argc, char *argv[])
219 {
220 if (argc != 2) {
221 fprintf(stderr, "Usage: %s /shm-path\n", argv[0]);
222 exit(EXIT_FAILURE);
223 }
224
225 char *shmpath = argv[1];
226
227 /* Create shared memory object and set its size to the size
228 of our structure */
229
230 int fd = shm_open(shmpath, O_CREAT | O_EXCL | O_RDWR,
231 S_IRUSR | S_IWUSR);
232 if (fd == -1)
233 errExit("shm_open");
234
235 if (ftruncate(fd, sizeof(struct shmbuf)) == -1)
236 errExit("ftruncate");
237
238 /* Map the object into the caller's address space */
239
240 struct shmbuf *shmp = mmap(NULL, sizeof(*shmp),
241 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 (int j = 0; j < shmp->cnt; j++)
262 shmp->buf[j] = toupper((unsigned char) shmp->buf[j]);
263
264 /* Post 'sem2' to tell the to tell 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 #include "pshm_ucase.h"
297
298 int
299 main(int argc, char *argv[])
300 {
301 if (argc != 3) {
302 fprintf(stderr, "Usage: %s /shm-path string\n", argv[0]);
303 exit(EXIT_FAILURE);
304 }
305
306 char *shmpath = argv[1];
307 char *string = argv[2];
308 size_t len = strlen(string);
309
310 if (len > BUF_SIZE) {
311 fprintf(stderr, "String is too long\n");
312 exit(EXIT_FAILURE);
313 }
314
315 /* Open the existing shared memory object and map it
316 into the caller's address space */
317
318 int fd = shm_open(shmpath, O_RDWR, 0);
319 if (fd == -1)
320 errExit("shm_open");
321
322 struct shmbuf *shmp = mmap(NULL, sizeof(*shmp),
323 PROT_READ | PROT_WRITE,
324 MAP_SHARED, fd, 0);
325 if (shmp == MAP_FAILED)
326 errExit("mmap");
327
328 /* Copy data into the shared memory object */
329
330 shmp->cnt = len;
331 memcpy(&shmp->buf, string, len);
332
333 /* Tell peer that it can now access shared memory */
334
335 if (sem_post(&shmp->sem1) == -1)
336 errExit("sem_post");
337
338 /* Wait until peer says that it has finished accessing
339 the shared memory */
340
341 if (sem_wait(&shmp->sem2) == -1)
342 errExit("sem_wait");
343
344 /* Write modified data in shared memory to standard output */
345
346 write(STDOUT_FILENO, &shmp->buf, len);
347 write(STDOUT_FILENO, "\n", 1);
348
349 exit(EXIT_SUCCESS);
350 }
351
353 close(2), fchmod(2), fchown(2), fcntl(2), fstat(2), ftruncate(2),
354 memfd_create(2), mmap(2), open(2), umask(2), shm_overview(7)
355
357 This page is part of release 5.10 of the Linux man-pages project. A
358 description of the project, information about reporting bugs, and the
359 latest version of this page, can be found at
360 https://www.kernel.org/doc/man-pages/.
361
362
363
364Linux 2020-11-01 SHM_OPEN(3)