1SHMOP(2)                      System Calls Manual                     SHMOP(2)
2
3
4

NAME

6       shmat, shmdt - System V shared memory operations
7

LIBRARY

9       Standard C library (libc, -lc)
10

SYNOPSIS

12       #include <sys/shm.h>
13
14       void *shmat(int shmid, const void *_Nullable shmaddr, int shmflg);
15       int shmdt(const void *shmaddr);
16

DESCRIPTION

18   shmat()
19       shmat() attaches the System V shared memory segment identified by shmid
20       to the address space of the calling process.  The attaching address  is
21       specified by shmaddr with one of the following criteria:
22
23       •  If  shmaddr  is  NULL,  the system chooses a suitable (unused) page-
24          aligned address to attach the segment.
25
26       •  If shmaddr isn't NULL and SHM_RND is specified in shmflg, the attach
27          occurs  at  the address equal to shmaddr rounded down to the nearest
28          multiple of SHMLBA.
29
30       •  Otherwise, shmaddr must be a page-aligned address at which  the  at‐
31          tach occurs.
32
33       In  addition  to  SHM_RND,  the following flags may be specified in the
34       shmflg bit-mask argument:
35
36       SHM_EXEC (Linux-specific; since Linux 2.6.9)
37              Allow the contents of the segment to be  executed.   The  caller
38              must have execute permission on the segment.
39
40       SHM_RDONLY
41              Attach  the segment for read-only access.  The process must have
42              read permission for the segment.  If this flag is not specified,
43              the  segment  is  attached  for  read  and write access, and the
44              process must have read and write  permission  for  the  segment.
45              There is no notion of a write-only shared memory segment.
46
47       SHM_REMAP (Linux-specific)
48              This  flag  specifies that the mapping of the segment should re‐
49              place any existing mapping in the range starting at shmaddr  and
50              continuing  for  the  size of the segment.  (Normally, an EINVAL
51              error would result if a mapping already exists in  this  address
52              range.)  In this case, shmaddr must not be NULL.
53
54       The  brk(2)  value of the calling process is not altered by the attach.
55       The segment will automatically be detached at process exit.   The  same
56       segment  may  be  attached  as a read and as a read-write one, and more
57       than once, in the process's address space.
58
59       A successful shmat() call updates the members of the shmid_ds structure
60       (see shmctl(2)) associated with the shared memory segment as follows:
61
62shm_atime is set to the current time.
63
64shm_lpid is set to the process-ID of the calling process.
65
66shm_nattch is incremented by one.
67
68   shmdt()
69       shmdt() detaches the shared memory segment located at the address spec‐
70       ified by shmaddr from the address space of the  calling  process.   The
71       to-be-detached segment must be currently attached with shmaddr equal to
72       the value returned by the attaching shmat() call.
73
74       On a successful shmdt() call, the system updates  the  members  of  the
75       shmid_ds  structure  associated  with the shared memory segment as fol‐
76       lows:
77
78shm_dtime is set to the current time.
79
80shm_lpid is set to the process-ID of the calling process.
81
82shm_nattch is decremented by one.  If it becomes 0 and  the  segment
83          is marked for deletion, the segment is deleted.
84

RETURN VALUE

86       On  success,  shmat() returns the address of the attached shared memory
87       segment; on error, (void *) -1 is returned, and errno is set  to  indi‐
88       cate the error.
89
90       On  success,  shmdt()  returns 0; on error -1 is returned, and errno is
91       set to indicate the error.
92

ERRORS

94       shmat() can fail with one of the following errors:
95
96       EACCES The calling process does not have the required  permissions  for
97              the  requested  attach type, and does not have the CAP_IPC_OWNER
98              capability in the user namespace that governs its IPC namespace.
99
100       EIDRM  shmid points to a removed identifier.
101
102       EINVAL Invalid shmid  value,  unaligned  (i.e.,  not  page-aligned  and
103              SHM_RND  was  not  specified) or invalid shmaddr value, or can't
104              attach segment  at  shmaddr,  or  SHM_REMAP  was  specified  and
105              shmaddr was NULL.
106
107       ENOMEM Could not allocate memory for the descriptor or for the page ta‐
108              bles.
109
110       shmdt() can fail with one of the following errors:
111
112       EINVAL There is no shared  memory  segment  attached  at  shmaddr;  or,
113              shmaddr is not aligned on a page boundary.
114

STANDARDS

116       POSIX.1-2008.
117

HISTORY

119       POSIX.1-2001, SVr4.
120
121       In  SVID  3  (or perhaps earlier), the type of the shmaddr argument was
122       changed from char * into const void *, and the returned type of shmat()
123       from char * into void *.
124

NOTES

126       After  a  fork(2),  the  child inherits the attached shared memory seg‐
127       ments.
128
129       After an execve(2), all attached shared memory  segments  are  detached
130       from the process.
131
132       Upon  _exit(2),  all  attached shared memory segments are detached from
133       the process.
134
135       Using shmat() with shmaddr equal to NULL is the preferred, portable way
136       of  attaching a shared memory segment.  Be aware that the shared memory
137       segment attached in this way may be attached at different addresses  in
138       different  processes.   Therefore,  any  pointers maintained within the
139       shared memory must be made relative (typically to the starting  address
140       of the segment), rather than absolute.
141
142       On  Linux,  it is possible to attach a shared memory segment even if it
143       is already marked to be deleted.  However,  POSIX.1  does  not  specify
144       this behavior and many other implementations do not support it.
145
146       The following system parameter affects shmat():
147
148       SHMLBA Segment low boundary address multiple.  When explicitly specify‐
149              ing an attach address in a call to shmat(),  the  caller  should
150              ensure  that  the  address is a multiple of this value.  This is
151              necessary on some architectures, in order either to ensure  good
152              CPU  cache  performance  or to ensure that different attaches of
153              the same segment have consistent views  within  the  CPU  cache.
154              SHMLBA  is  normally some multiple of the system page size.  (On
155              many Linux architectures, SHMLBA is the same as the system  page
156              size.)
157
158       The  implementation places no intrinsic per-process limit on the number
159       of shared memory segments (SHMSEG).
160

EXAMPLES

162       The two programs shown below exchange a string using  a  shared  memory
163       segment.   Further  details about the programs are given below.  First,
164       we show a shell session demonstrating their use.
165
166       In one terminal window, we run the "reader" program,  which  creates  a
167       System  V shared memory segment and a System V semaphore set.  The pro‐
168       gram prints out the IDs of the created objects, and then waits for  the
169       semaphore to change value.
170
171           $ ./svshm_string_read
172           shmid = 1114194; semid = 15
173
174       In  another terminal window, we run the "writer" program.  The "writer"
175       program takes three command-line arguments: the IDs of the shared  mem‐
176       ory  segment  and  semaphore set created by the "reader", and a string.
177       It attaches the existing shared memory segment, copies  the  string  to
178       the shared memory, and modifies the semaphore value.
179
180           $ ./svshm_string_write 1114194 15 'Hello, world'
181
182       Returning  to  the  terminal where the "reader" is running, we see that
183       the program has ceased waiting on the semaphore  and  has  printed  the
184       string that was copied into the shared memory segment by the writer:
185
186           Hello, world
187
188   Program source: svshm_string.h
189       The following header file is included by the "reader" and "writer" pro‐
190       grams:
191
192           /* svshm_string.h
193
194              Licensed under GNU General Public License v2 or later.
195           */
196           #include <sys/types.h>
197           #include <sys/ipc.h>
198           #include <sys/shm.h>
199           #include <sys/sem.h>
200           #include <stdio.h>
201           #include <stdlib.h>
202           #include <string.h>
203
204           #define errExit(msg)    do { perror(msg); exit(EXIT_FAILURE); \
205                                   } while (0)
206
207           union semun {                   /* Used in calls to semctl() */
208               int                 val;
209               struct semid_ds *   buf;
210               unsigned short *    array;
211           #if defined(__linux__)
212               struct seminfo *    __buf;
213           #endif
214           };
215
216           #define MEM_SIZE 4096
217
218   Program source: svshm_string_read.c
219       The "reader" program creates a shared memory segment  and  a  semaphore
220       set  containing  one semaphore.  It then attaches the shared memory ob‐
221       ject into its address space and initializes the semaphore value  to  1.
222       Finally, the program waits for the semaphore value to become 0, and af‐
223       terwards prints the string that has been copied into the shared  memory
224       segment by the "writer".
225
226           /* svshm_string_read.c
227
228              Licensed under GNU General Public License v2 or later.
229           */
230           #include <stdio.h>
231           #include <stdlib.h>
232           #include <sys/ipc.h>
233           #include <sys/sem.h>
234           #include <sys/shm.h>
235
236           #include "svshm_string.h"
237
238           int
239           main(void)
240           {
241               int            semid, shmid;
242               char           *addr;
243               union semun    arg, dummy;
244               struct sembuf  sop;
245
246               /* Create shared memory and semaphore set containing one
247                  semaphore. */
248
249               shmid = shmget(IPC_PRIVATE, MEM_SIZE, IPC_CREAT | 0600);
250               if (shmid == -1)
251                   errExit("shmget");
252
253               semid = semget(IPC_PRIVATE, 1, IPC_CREAT | 0600);
254               if (semid == -1)
255                   errExit("semget");
256
257               /* Attach shared memory into our address space. */
258
259               addr = shmat(shmid, NULL, SHM_RDONLY);
260               if (addr == (void *) -1)
261                   errExit("shmat");
262
263               /* Initialize semaphore 0 in set with value 1. */
264
265               arg.val = 1;
266               if (semctl(semid, 0, SETVAL, arg) == -1)
267                   errExit("semctl");
268
269               printf("shmid = %d; semid = %d\n", shmid, semid);
270
271               /* Wait for semaphore value to become 0. */
272
273               sop.sem_num = 0;
274               sop.sem_op = 0;
275               sop.sem_flg = 0;
276
277               if (semop(semid, &sop, 1) == -1)
278                   errExit("semop");
279
280               /* Print the string from shared memory. */
281
282               printf("%s\n", addr);
283
284               /* Remove shared memory and semaphore set. */
285
286               if (shmctl(shmid, IPC_RMID, NULL) == -1)
287                   errExit("shmctl");
288               if (semctl(semid, 0, IPC_RMID, dummy) == -1)
289                   errExit("semctl");
290
291               exit(EXIT_SUCCESS);
292           }
293
294   Program source: svshm_string_write.c
295       The  writer  program takes three command-line arguments: the IDs of the
296       shared memory segment and semaphore set that have already been  created
297       by  the  "reader", and a string.  It attaches the shared memory segment
298       into its address space, and then decrements the semaphore value to 0 in
299       order  to  inform  the "reader" that it can now examine the contents of
300       the shared memory.
301
302           /* svshm_string_write.c
303
304              Licensed under GNU General Public License v2 or later.
305           */
306           #include <stdio.h>
307           #include <stdlib.h>
308           #include <string.h>
309           #include <sys/sem.h>
310           #include <sys/shm.h>
311
312           #include "svshm_string.h"
313
314           int
315           main(int argc, char *argv[])
316           {
317               int            semid, shmid;
318               char           *addr;
319               size_t         len;
320               struct sembuf  sop;
321
322               if (argc != 4) {
323                   fprintf(stderr, "Usage: %s shmid semid string\n", argv[0]);
324                   exit(EXIT_FAILURE);
325               }
326
327               len = strlen(argv[3]) + 1;  /* +1 to include trailing '\0' */
328               if (len > MEM_SIZE) {
329                   fprintf(stderr, "String is too big!\n");
330                   exit(EXIT_FAILURE);
331               }
332
333               /* Get object IDs from command-line. */
334
335               shmid = atoi(argv[1]);
336               semid = atoi(argv[2]);
337
338               /* Attach shared memory into our address space and copy string
339                  (including trailing null byte) into memory. */
340
341               addr = shmat(shmid, NULL, 0);
342               if (addr == (void *) -1)
343                   errExit("shmat");
344
345               memcpy(addr, argv[3], len);
346
347               /* Decrement semaphore to 0. */
348
349               sop.sem_num = 0;
350               sop.sem_op = -1;
351               sop.sem_flg = 0;
352
353               if (semop(semid, &sop, 1) == -1)
354                   errExit("semop");
355
356               exit(EXIT_SUCCESS);
357           }
358

SEE ALSO

360       brk(2),  mmap(2),  shmctl(2),  shmget(2),  capabilities(7),   shm_over‐
361       view(7), sysvipc(7)
362
363
364
365Linux man-pages 6.04              2023-03-30                          SHMOP(2)
Impressum