Upload Tizen:Base source
[framework/base/util-linux-ng.git] / sys-utils / ipc.info
1 This is ipc.info, produced by makeinfo version 4.7 from ipc.texi.
2
3    This file documents the System V style inter process communication
4 primitives available under linux.
5
6    Copyright (C) 1992  krishna balasubramanian
7
8    Permission is granted to use this material and the accompanying
9 programs within the terms of the GNU GPL.
10
11 INFO-DIR-SECTION Miscellaneous
12 START-INFO-DIR-ENTRY
13 * ipc: (ipc).           System V style inter process communication
14 END-INFO-DIR-ENTRY
15
16 \1f
17 File: ipc.info,  Node: Top,  Next: Overview,  Prev: Notes,  Up: (dir)
18
19 1 System V IPC.
20 ***************
21
22 These facilities are provided to maintain compatibility with programs
23 developed on system V unix systems and others that rely on these system
24 V mechanisms to accomplish inter process communication (IPC).
25
26    The specifics described here are applicable to the Linux
27 implementation.  Other implementations may do things slightly
28 differently.
29
30 * Menu:
31
32 * Overview::            What is system V ipc? Overall mechanisms.
33 * Messages::            System calls for message passing.
34 * Semaphores::          System calls for semaphores.
35 * Shared Memory::       System calls for shared memory access.
36 * Notes::               Miscellaneous notes.
37
38 \1f
39 File: ipc.info,  Node: Overview,  Next: example,  Prev: Top,  Up: Top
40
41 1.1 Overview
42 ============
43
44 System V IPC consists of three mechanisms:
45
46    * Messages : exchange messages with any process or server.
47
48    * Semaphores : allow unrelated processes to synchronize execution.
49
50    * Shared memory : allow unrelated processes to share memory.
51
52 * Menu:
53
54 * example::     Using shared memory.
55 * perms::       Description of access permissions.
56 * syscalls::    Overview of ipc system calls.
57
58    Access to all resources is permitted on the basis of permissions set
59 up when the resource was created.
60
61    A resource here consists of message queue, a semaphore set (array)
62 or a shared memory segment.
63
64    A resource must first be allocated by a creator before it is used.
65 The creator can assign a different owner. After use the resource must
66 be explicitly destroyed by the creator or owner.
67
68    A resource is identified by a numeric ID. Typically a creator
69 defines a KEY that may be used to access the resource. The user process
70 may then use this KEY in the "get" system call to obtain the ID for the
71 corresponding resource. This ID is then used for all further access. A
72 library call "ftok" is provided to translate pathnames or strings to
73 numeric keys.
74
75    There are system and implementation defined limits on the number and
76 sizes of resources of any given type. Some of these are imposed by the
77 implementation and others by the system administrator when configuring
78 the kernel (*Note msglimits::, *Note semlimits::, *Note shmlimits::).
79
80    There is an `msqid_ds', `semid_ds' or `shmid_ds' struct associated
81 with each message queue, semaphore array or shared segment.  Each ipc
82 resource has an associated `ipc_perm' struct which defines the creator,
83 owner, access perms ..etc.., for the resource.  These structures are
84 detailed in the following sections.
85
86 \1f
87 File: ipc.info,  Node: example,  Next: perms,  Prev: Overview,  Up: Overview
88
89 1.2 example
90 ===========
91
92 Here is a code fragment with pointers on how to use shared memory. The
93 same methods are applicable to other resources.
94
95    In a typical access sequence the creator allocates a new instance of
96 the resource with the `get' system call using the IPC_CREAT flag.
97
98 creator process:
99      #include <sys/shm.h>
100      int id;
101      key_t key;
102      char proc_id = 'C';
103      int size = 0x5000; /* 20 K */
104      int flags = 0664 | IPC_CREAT;              /* read-only for others */
105
106      key = ftok ("~creator/ipckey", proc_id);
107      id = shmget (key, size, flags);
108      exit (0);  /* quit leaving resource allocated */
109
110 Users then gain access to the resource using the same key.
111 Client process:
112      #include <sys/shm.h>
113      char *shmaddr;
114      int id;
115      key_t key;
116      char proc_id = 'C';
117
118      key = ftok ("~creator/ipckey", proc_id);
119
120      id = shmget (key, 0, 004);         /* default size   */
121      if (id == -1)
122            perror ("shmget ...");
123
124      shmaddr = shmat (id, 0, SHM_RDONLY); /* attach segment for reading */
125      if (shmaddr == (char *) -1)
126            perror ("shmat ...");
127
128      local_var = *(shmaddr + 3);        /* read segment etc. */
129
130      shmdt (shmaddr);           /* detach segment */
131
132 When the resource is no longer needed the creator should remove it.
133 Creator/owner process 2:
134      key = ftok ("~creator/ipckey", proc_id)
135      id = shmget (key, 0, 0);
136      shmctl (id, IPC_RMID, NULL);
137
138 \1f
139 File: ipc.info,  Node: perms,  Next: syscalls,  Prev: example,  Up: Overview
140
141 1.3 Permissions
142 ===============
143
144 Each resource has an associated `ipc_perm' struct which defines the
145 creator, owner and access perms for the resource.
146
147      struct ipc_perm
148              key_t key;    /* set by creator */
149              ushort uid;   /* owner euid and egid */
150              ushort gid;
151              ushort cuid;  /* creator euid and egid */
152              ushort cgid;
153              ushort mode;  /* access modes in lower 9 bits */
154              ushort seq;   /* sequence number */
155
156    The creating process is the default owner. The owner can be
157 reassigned by the creator and has creator perms. Only the owner,
158 creator or super-user can delete the resource.
159
160    The lowest nine bits of the flags parameter supplied by the user to
161 the system call are compared with the values stored in `ipc_perms.mode'
162 to determine if the requested access is allowed. In the case that the
163 system call creates the resource, these bits are initialized from the
164 user supplied value.
165
166    As for files, access permissions are specified as read, write and
167 exec for user, group or other (though the exec perms are unused). For
168 example 0624 grants read-write to owner, write-only to group and
169 read-only access to others.
170
171    For shared memory, note that read-write access for segments is
172 determined by a separate flag which is not stored in the `mode' field.
173 Shared memory segments attached with write access can be read.
174
175    The `cuid', `cgid', `key' and `seq' fields cannot be changed by the
176 user.
177
178 \1f
179 File: ipc.info,  Node: syscalls,  Next: Messages,  Prev: perms,  Up: Overview
180
181 1.4 IPC system calls
182 ====================
183
184 This section provides an overview of the IPC system calls. See the
185 specific sections on each type of resource for details.
186
187    Each type of mechanism provides a "get", "ctl" and one or more "op"
188 system calls that allow the user to create or procure the resource
189 (get), define its behaviour or destroy it (ctl) and manipulate the
190 resources (op).
191
192 1.4.1 The "get" system calls
193 ----------------------------
194
195 The `get' call typically takes a KEY and returns a numeric ID that is
196 used for further access.  The ID is an index into the resource table. A
197 sequence number is maintained and incremented when a resource is
198 destroyed so that access using an obsolete ID is likely to fail.
199
200    The user also specifies the permissions and other behaviour
201 charecteristics for the current access. The flags are or-ed with the
202 permissions when invoking system calls as in:
203      msgflg = IPC_CREAT | IPC_EXCL | 0666;
204      id = msgget (key, msgflg);
205
206    * `key' : IPC_PRIVATE => new instance of resource is initialized.
207
208    * `flags' :
209           IPC_CREAT : resource created for KEY if it does not exist.
210
211           IPC_CREAT | IPC_EXCL : fail if resource exists for KEY.
212
213    * returns : an identifier used for all further access to the
214      resource.
215
216    Note that IPC_PRIVATE is not a flag but a special `key' that ensures
217 (when the call is successful) that a new resource is created.
218
219    Use of IPC_PRIVATE does not make the resource inaccessible to other
220 users. For this you must set the access permissions appropriately.
221
222    There is currently no way for a process to ensure exclusive access
223 to a resource. IPC_CREAT | IPC_EXCL only ensures (on success) that a new
224 resource was initialized. It does not imply exclusive access.
225
226 See Also : *Note msgget::, *Note semget::, *Note shmget::.
227
228 1.4.2 The "ctl" system calls
229 ----------------------------
230
231 Provides or alters the information stored in the structure that
232 describes the resource indexed by ID.
233
234      #include <sys/msg.h>
235      struct msqid_ds buf;
236      err = msgctl (id, IPC_STAT, &buf);
237      if (err)
238              !$#%*
239      else
240              printf ("creator uid = %d\n", buf.msg_perm.cuid);
241              ....
242
243 Commands supported by all `ctl' calls:
244    * IPC_STAT : read info on resource  specified by id into user
245      allocated buffer. The user must have read access to the resource.
246
247    * IPC_SET : write info from buffer into resource data structure. The
248      user must be owner creator or super-user.
249
250    * IPC_RMID : remove resource. The user must be the owner, creator or
251      super-user.
252
253    The IPC_RMID command results in immediate removal of a message queue
254 or semaphore array. Shared memory segments however, are only destroyed
255 upon the last detach after IPC_RMID is executed.
256
257    The `semctl' call provides a number of command options that allow
258 the user to determine or set the values of the semaphores in an array.
259
260 See Also: *Note msgctl::, *Note semctl::, *Note shmctl::.
261
262 1.4.3 The "op" system calls
263 ---------------------------
264
265 Used to send or receive messages, read or alter semaphore values,
266 attach or detach shared memory segments.  The IPC_NOWAIT flag will
267 cause the operation to fail with error EAGAIN if the process has to
268 wait on the call.
269
270 `flags' : IPC_NOWAIT  => return with error if a wait is required.
271
272 See Also: *Note msgsnd::,*Note msgrcv::,*Note semop::,*Note shmat::,
273 *Note shmdt::.
274
275 \1f
276 File: ipc.info,  Node: Messages,  Next: msgget,  Prev: syscalls,  Up: Top
277
278 1.5 Messages
279 ============
280
281 A message resource is described by a struct `msqid_ds' which is
282 allocated and initialized when the resource is created. Some fields in
283 `msqid_ds' can then be altered (if desired) by invoking `msgctl'.  The
284 memory used by the resource is released when it is destroyed by a
285 `msgctl' call.
286
287      struct msqid_ds
288          struct ipc_perm msg_perm;
289          struct msg *msg_first;  /* first message on queue (internal) */
290          struct msg *msg_last;   /* last message in queue (internal) */
291          time_t msg_stime;       /* last msgsnd time */
292          time_t msg_rtime;       /* last msgrcv time */
293          time_t msg_ctime;       /* last change time */
294          struct wait_queue *wwait; /* writers waiting (internal) */
295          struct wait_queue *rwait; /* readers waiting (internal) */
296          ushort msg_cbytes;      /* number of bytes used on queue */
297          ushort msg_qnum;        /* number of messages in queue */
298          ushort msg_qbytes;      /* max number of bytes on queue */
299          ushort msg_lspid;       /* pid of last msgsnd */
300          ushort msg_lrpid;       /* pid of last msgrcv */
301
302    To send or receive a message the user allocates a structure that
303 looks like a `msgbuf' but with an array `mtext' of the required size.
304 Messages have a type (positive integer) associated with them so that
305 (for example) a listener can choose to receive only messages of a given
306 type.
307
308      struct msgbuf
309          long mtype;      type of message (*Note msgrcv::).
310          char mtext[1];   message text .. why is this not a ptr?
311
312    The user must have write permissions to send and read permissions to
313 receive messages on a queue.
314
315    When `msgsnd' is invoked, the user's message is copied into an
316 internal struct `msg' and added to the queue. A `msgrcv' will then read
317 this message and free the associated struct `msg'.
318
319 * Menu:
320
321 * msgget::
322 * msgsnd::
323 * msgrcv::
324 * msgctl::
325 * msglimits:: Implementation defined limits.
326
327 \1f
328 File: ipc.info,  Node: msgget,  Next: msgsnd,  Prev: Messages,  Up: Messages
329
330 1.5.1 msgget
331 ------------
332
333 A message queue is allocated by a msgget system call :
334
335      msqid = msgget (key_t key, int msgflg);
336
337    * `key': an integer usually got from `ftok()' or IPC_PRIVATE.
338
339    * `msgflg':
340           IPC_CREAT : used to create a new resource if it does not
341           already exist.
342
343           IPC_EXCL | IPC_CREAT : used to ensure failure of the call if
344           the resource already exists.
345
346           rwxrwxrwx : access permissions.
347
348    * returns: msqid (an integer used for all further access) on success.
349      -1 on failure.
350
351    A message queue is allocated if there is no resource corresponding
352 to the given key. The access permissions specified are then copied into
353 the `msg_perm' struct and the fields in `msqid_ds' initialized. The
354 user must use the IPC_CREAT flag or key = IPC_PRIVATE, if a new
355 instance is to be allocated. If a resource corresponding to KEY already
356 exists, the access permissions are verified.
357
358 Errors:
359 EACCES : (procure) Do not have permission for requested access.
360 EEXIST : (allocate) IPC_CREAT | IPC_EXCL specified and resource exists.
361 EIDRM  : (procure) The resource was removed.
362 ENOSPC : All id's are taken (max of MSGMNI id's system-wide).
363 ENOENT : Resource does not exist and IPC_CREAT not specified.
364 ENOMEM : A new `msqid_ds' was to be created but ... nomem.
365
366 \1f
367 File: ipc.info,  Node: msgsnd,  Next: msgrcv,  Prev: msgget,  Up: Messages
368
369 1.5.2 msgsnd
370 ------------
371
372      int msgsnd (int msqid, struct msgbuf *msgp, int msgsz, int msgflg);
373
374    * `msqid' : id obtained by a call to msgget.
375
376    * `msgsz' : size of msg text (`mtext') in bytes.
377
378    * `msgp' : message to be sent. (msgp->mtype must be positive).
379
380    * `msgflg' : IPC_NOWAIT.
381
382    * returns : msgsz on success. -1 on error.
383
384    The message text and type are stored in the internal `msg'
385 structure. `msg_cbytes', `msg_qnum', `msg_lspid', and `msg_stime'
386 fields are updated. Readers waiting on the queue are awakened.
387
388 Errors:
389 EACCES : Do not have write permission on queue.
390 EAGAIN : IPC_NOWAIT specified and queue is full.
391 EFAULT : msgp not accessible.
392 EIDRM  : The message queue was removed.
393 EINTR  : Full queue ... would have slept but ... was interrupted.
394 EINVAL : mtype < 1, msgsz > MSGMAX, msgsz < 0, msqid < 0 or unused.
395 ENOMEM : Could not allocate space for header and text.
396 \1f
397 File: ipc.info,  Node: msgrcv,  Next: msgctl,  Prev: msgsnd,  Up: Messages
398
399 1.5.3 msgrcv
400 ------------
401
402      int msgrcv (int msqid, struct msgbuf *msgp, int msgsz, long msgtyp,
403                         int msgflg);
404
405    * msqid  : id obtained by a call to msgget.
406
407    * msgsz  : maximum size of message to receive.
408
409    * msgp   : allocated by user to store the message in.
410
411    * msgtyp :
412           0 => get first message on queue.
413
414           > 0 => get first message of matching type.
415
416           < 0 => get message with least type  which is <= abs(msgtyp).
417
418    * msgflg :
419           IPC_NOWAIT : Return immediately if message not found.
420
421           MSG_NOERROR : The message is truncated if it is larger than
422           msgsz.
423
424           MSG_EXCEPT : Used with msgtyp > 0 to receive any msg except
425           of specified type.
426
427    * returns : size of message if found. -1 on error.
428
429    The first message that meets the `msgtyp' specification is
430 identified. For msgtyp < 0, the entire queue is searched for the
431 message with the smallest type.
432
433    If its length is smaller than msgsz or if the user specified the
434 MSG_NOERROR flag, its text and type are copied to msgp->mtext and
435 msgp->mtype, and it is taken off the queue.
436
437    The `msg_cbytes', `msg_qnum', `msg_lrpid', and `msg_rtime' fields
438 are updated. Writers waiting on the queue are awakened.
439
440 Errors:
441 E2BIG  : msg bigger than msgsz and MSG_NOERROR not specified.
442 EACCES : Do not have permission for reading the queue.
443 EFAULT : msgp not accessible.
444 EIDRM  : msg queue was removed.
445 EINTR  : msg not found ... would have slept but ... was interrupted.
446 EINVAL : msgsz > msgmax or msgsz < 0, msqid < 0 or unused.
447 ENOMSG : msg of requested type not found and IPC_NOWAIT specified.
448
449 \1f
450 File: ipc.info,  Node: msgctl,  Next: msglimits,  Prev: msgrcv,  Up: Messages
451
452 1.5.4 msgctl
453 ------------
454
455      int msgctl (int msqid, int cmd, struct msqid_ds *buf);
456
457    * msqid  : id obtained by a call to msgget.
458
459    * buf    : allocated by user for reading/writing info.
460
461    * cmd    : IPC_STAT, IPC_SET, IPC_RMID (*Note syscalls::).
462
463    IPC_STAT results in the copy of the queue data structure into the
464 user supplied buffer.
465
466    In the case of IPC_SET, the queue size (`msg_qbytes') and the `uid',
467 `gid', `mode' (low 9 bits) fields of the `msg_perm' struct are set from
468 the user supplied values.  `msg_ctime' is updated.
469
470    Note that only the super user may increase the limit on the size of a
471 message queue beyond MSGMNB.
472
473    When the queue is destroyed (IPC_RMID), the sequence number is
474 incremented and all waiting readers and writers are awakened.  These
475 processes will then return with `errno' set to EIDRM.
476
477 Errors: EPERM  : Insufficient privilege to increase the size of the
478 queue (IPC_SET) or remove it (IPC_RMID).
479 EACCES : Do not have permission for reading the queue (IPC_STAT).
480 EFAULT : buf not accessible (IPC_STAT, IPC_SET).
481 EIDRM  : msg queue was removed.
482 EINVAL : invalid cmd, msqid < 0 or unused.
483
484 \1f
485 File: ipc.info,  Node: msglimits,  Next: Semaphores,  Prev: msgctl,  Up: Messages
486
487 1.5.5 Limis on Message Resources
488 --------------------------------
489
490 Sizeof various structures:
491      msqid_ds        52   /* 1 per message  queue .. dynamic */
492
493      msg             16   /* 1 for each message in system .. dynamic */
494
495      msgbuf           8   /* allocated by user */
496
497 Limits
498    * MSGMNI : number of message queue identifiers ... policy.
499
500    * MSGMAX : max size of message.  Header and message space allocated
501      on one page.  MSGMAX = (PAGE_SIZE - sizeof(struct msg)).
502      Implementation maximum MSGMAX = 4080.
503
504    * MSGMNB : default max size of a message queue ... policy.  The
505      super-user can increase the size of a queue beyond MSGMNB by a
506      `msgctl' call.
507
508 Unused or unimplemented:
509 MSGTQL  max number of message headers system-wide.
510 MSGPOOL total size in bytes of msg pool.
511
512 \1f
513 File: ipc.info,  Node: Semaphores,  Next: semget,  Prev: msglimits,  Up: Top
514
515 1.6 Semaphores
516 ==============
517
518 Each semaphore has a value >= 0. An id provides access to an array of
519 `nsems' semaphores. Operations such as read, increment or decrement
520 semaphores in a set are performed by the `semop' call which processes
521 `nsops' operations at a time. Each operation is specified in a struct
522 `sembuf' described below. The operations are applied only if all of
523 them succeed.
524
525    If you do not have a need for such arrays, you are probably better
526 off using the `test_bit', `set_bit' and  `clear_bit' bit-operations
527 defined in <asm/bitops.h>.
528
529    Semaphore operations may also be qualified by a SEM_UNDO flag which
530 results in the operation being undone when the process exits.
531
532    If a decrement cannot go through, a process will be put to sleep on
533 a queue waiting for the `semval' to increase unless it specifies
534 IPC_NOWAIT. A read operation can similarly result in a sleep on a queue
535 waiting for `semval' to become 0. (Actually there are two queues per
536 semaphore array).
537
538 A semaphore array is described by:
539      struct semid_ds
540        struct ipc_perm sem_perm;
541        time_t          sem_otime;      /* last semop time */
542        time_t          sem_ctime;      /* last change time */
543        struct wait_queue *eventn;         /* wait for a semval to increase */
544        struct wait_queue *eventz;      /* wait for a semval to become 0 */
545        struct sem_undo  *undo;         /* undo entries */
546        ushort          sem_nsems;      /* no. of semaphores in array */
547
548 Each semaphore is described internally by :
549      struct sem
550        short   sempid;         /* pid of last semop() */
551        ushort  semval;         /* current value */
552        ushort  semncnt;        /* num procs awaiting increase in semval */
553        ushort  semzcnt;        /* num procs awaiting semval = 0 */
554
555 * Menu:
556
557 * semget::
558 * semop::
559 * semctl::
560 * semlimits:: Limits imposed by this implementation.
561
562 \1f
563 File: ipc.info,  Node: semget,  Next: semop,  Prev: Semaphores,  Up: Semaphores
564
565 1.6.1 semget
566 ------------
567
568 A semaphore array is allocated by a semget system call:
569
570      semid = semget (key_t key, int nsems, int semflg);
571
572    * `key' : an integer usually got from `ftok' or IPC_PRIVATE
573
574    * `nsems' :
575           # of semaphores in array (0 <= nsems <= SEMMSL <= SEMMNS)
576
577           0 => dont care can be used when not creating the resource.
578           If successful you always get access to the entire array
579           anyway.
580
581    * semflg :
582           IPC_CREAT used to create a new resource
583
584           IPC_EXCL used with IPC_CREAT to ensure failure if the
585           resource exists.
586
587           rwxrwxrwx  access permissions.
588
589    * returns : semid on success. -1 on failure.
590
591    An array of nsems semaphores is allocated if there is no resource
592 corresponding to the given key. The access permissions specified are
593 then copied into the `sem_perm' struct for the array along with the
594 user-id etc. The user must use the IPC_CREAT flag or key = IPC_PRIVATE
595 if a new resource is to be created.
596
597 Errors:
598 EINVAL : nsems not in above range (allocate).
599 nsems greater than number in array (procure).
600 EEXIST : (allocate) IPC_CREAT | IPC_EXCL specified and resource exists.
601 EIDRM  : (procure) The resource was removed.
602 ENOMEM : could not allocate space for semaphore array.
603 ENOSPC : No arrays available (SEMMNI), too few semaphores available
604 (SEMMNS).
605 ENOENT : Resource does not exist and IPC_CREAT not specified.
606 EACCES : (procure) do not have permission for specified access.
607
608 \1f
609 File: ipc.info,  Node: semop,  Next: semctl,  Prev: semget,  Up: Semaphores
610
611 1.6.2 semop
612 -----------
613
614 Operations on semaphore arrays are performed by calling semop :
615
616      int semop (int semid, struct sembuf *sops, unsigned nsops);
617
618    * semid : id obtained by a call to semget.
619
620    * sops : array of semaphore operations.
621
622    * nsops : number of operations in array (0 < nsops < SEMOPM).
623
624    * returns : semval for last operation. -1 on failure.
625
626 Operations are described by a structure sembuf:
627      struct sembuf
628          ushort  sem_num;        /* semaphore index in array */
629          short   sem_op;         /* semaphore operation */
630          short   sem_flg;        /* operation flags */
631
632    The value `sem_op' is to be added (signed) to the current value
633 semval of the semaphore with index sem_num (0 .. nsems -1) in the set.
634 Flags recognized in sem_flg are IPC_NOWAIT and SEM_UNDO.
635
636 Two kinds of operations can result in wait:
637   1. If sem_op is 0 (read operation) and semval is non-zero, the process
638      sleeps on a queue waiting for semval to become zero or returns with
639      error EAGAIN if (IPC_NOWAIT | sem_flg) is true.
640
641   2. If (sem_op < 0) and (semval + sem_op < 0), the process either
642      sleeps on a queue waiting for semval to increase or returns with
643      error EAGAIN if (sem_flg & IPC_NOWAIT) is true.
644
645    The array sops is first read in and preliminary checks performed on
646 the arguments. The operations are parsed to determine if any of them
647 needs write permissions or requests an undo operation.
648
649    The operations are then tried and the process sleeps if any operation
650 that does not specify IPC_NOWAIT cannot go through. If a process sleeps
651 it repeats these checks on waking up. If any operation that requests
652 IPC_NOWAIT, cannot go through at any stage, the call returns with errno
653 set to EAGAIN.
654
655    Finally, operations are committed when all go through without an
656 intervening sleep. Processes waiting on the zero_queue or
657 increment_queue are awakened if any of the semval's becomes zero or is
658 incremented respectively.
659
660 Errors:
661 E2BIG  : nsops > SEMOPM.
662 EACCES : Do not have permission for requested (read/alter) access.
663 EAGAIN : An operation with IPC_NOWAIT specified could not go through.
664 EFAULT : The array sops is not accessible.
665 EFBIG  : An operation had semnum >= nsems.
666 EIDRM  : The resource was removed.
667 EINTR  : The process was interrupted on its way to a wait queue.
668 EINVAL : nsops is 0, semid < 0 or unused.
669 ENOMEM : SEM_UNDO requested. Could not allocate space for undo
670 structure.
671 ERANGE : sem_op + semval > SEMVMX for some operation.
672
673 \1f
674 File: ipc.info,  Node: semctl,  Next: semlimits,  Prev: semop,  Up: Semaphores
675
676 1.6.3 semctl
677 ------------
678
679      int semctl (int semid, int semnum, int cmd, union semun arg);
680
681    * semid : id obtained by a call to semget.
682
683    * cmd :
684           GETPID  return pid for the process that executed the last
685           semop.
686
687           GETVAL  return semval of semaphore with index semnum.
688
689           GETNCNT return number of processes waiting for semval to
690           increase.
691
692           GETZCNT return number of processes waiting for semval to
693           become 0
694
695           SETVAL  set semval = arg.val.
696
697           GETALL  read all semval's into arg.array.
698
699           SETALL  set all semval's with values given in arg.array.
700
701    * returns : 0 on success or as given above. -1 on failure.
702
703    The first 4 operate on the semaphore with index semnum in the set.
704 The last two operate on all semaphores in the set.
705
706    `arg' is a union :
707      union semun
708          int val;               value for SETVAL.
709          struct semid_ds *buf;  buffer for IPC_STAT and IPC_SET.
710          ushort *array;         array for GETALL and SETALL
711
712    * IPC_SET, SETVAL, SETALL : sem_ctime is updated.
713
714    * SETVAL, SETALL : Undo entries are cleared for altered semaphores in
715      all processes. Processes sleeping on the wait queues are awakened
716      if a semval becomes 0 or increases.
717
718    * IPC_SET : sem_perm.uid, sem_perm.gid, sem_perm.mode are updated
719      from user supplied values.
720
721 Errors: EACCES : do not have permission for specified access.
722 EFAULT : arg is not accessible.
723 EIDRM  : The resource was removed.
724 EINVAL : semid < 0 or semnum < 0 or semnum >= nsems.
725 EPERM  : IPC_RMID, IPC_SET ... not creator, owner or super-user.
726 ERANGE : arg.array[i].semval > SEMVMX or < 0 for some i.
727
728 \1f
729 File: ipc.info,  Node: semlimits,  Next: Shared Memory,  Prev: semctl,  Up: Semaphores
730
731 1.6.4 Limits on Semaphore Resources
732 -----------------------------------
733
734 Sizeof various structures:
735      semid_ds    44   /* 1 per semaphore array .. dynamic */
736      sem          8   /* 1 for each semaphore in system .. dynamic */
737      sembuf       6   /* allocated by user */
738      sem_undo    20   /* 1 for each undo request .. dynamic */
739
740 Limits :
741    * SEMVMX  32767  semaphore maximum value (short).
742
743    * SEMMNI  number of semaphore identifiers (or arrays) system
744      wide...policy.
745
746    * SEMMSL  maximum  number  of semaphores per id.  1 semid_ds per
747      array, 1 struct sem per semaphore => SEMMSL =  (PAGE_SIZE -
748      sizeof(semid_ds)) / sizeof(sem).  Implementation maximum SEMMSL =
749      500.
750
751    * SEMMNS  maximum number of semaphores system wide ... policy.
752      Setting SEMMNS >= SEMMSL*SEMMNI makes it irrelevent.
753
754    * SEMOPM     Maximum number of operations in one semop
755      call...policy.
756
757 Unused or unimplemented:
758 SEMAEM  adjust on exit max value.
759 SEMMNU  number of undo structures system-wide.
760 SEMUME  maximum number of undo entries per process.
761
762 \1f
763 File: ipc.info,  Node: Shared Memory,  Next: shmget,  Prev: semlimits,  Up: Top
764
765 1.7 Shared Memory
766 =================
767
768 Shared memory is distinct from the sharing of read-only code pages or
769 the sharing of unaltered data pages that is available due to the
770 copy-on-write mechanism. The essential difference is that the shared
771 pages are dirty (in the case of Shared memory) and can be made to
772 appear at a convenient location in the process' address space.
773
774 A shared segment is described by :
775      struct shmid_ds
776          struct  ipc_perm shm_perm;
777          int     shm_segsz;              /* size of segment (bytes) */
778          time_t  shm_atime;              /* last attach time */
779          time_t  shm_dtime;              /* last detach time */
780          time_t  shm_ctime;              /* last change time */
781          ulong   *shm_pages;             /* internal page table */
782          ushort  shm_cpid;               /* pid, creator */
783          ushort  shm_lpid;               /* pid, last operation */
784          short   shm_nattch;             /* no. of current attaches */
785
786    A shmget allocates a shmid_ds and an internal page table. A shmat
787 maps the segment into the process' address space with pointers into the
788 internal page table and the actual pages are faulted in as needed. The
789 memory associated with the segment must be explicitly destroyed by
790 calling shmctl with IPC_RMID.
791
792 * Menu:
793
794 * shmget::
795 * shmat::
796 * shmdt::
797 * shmctl::
798 * shmlimits:: Limits imposed by this implementation.
799
800 \1f
801 File: ipc.info,  Node: shmget,  Next: shmat,  Prev: Shared Memory,  Up: Shared Memory
802
803 1.7.1 shmget
804 ------------
805
806 A shared memory segment is allocated by a shmget system call:
807
808      int shmget(key_t key, int size, int shmflg);
809
810    * key : an integer usually got from `ftok' or IPC_PRIVATE
811
812    * size : size of the segment in bytes (SHMMIN <= size <= SHMMAX).
813
814    * shmflg :
815           IPC_CREAT used to create a new resource
816
817           IPC_EXCL used with IPC_CREAT to ensure failure if the
818           resource exists.
819
820           rwxrwxrwx  access permissions.
821
822    * returns : shmid on success. -1 on failure.
823
824    A descriptor for a shared memory segment is allocated if there isn't
825 one corresponding to the given key. The access permissions specified are
826 then copied into the `shm_perm' struct for the segment along with the
827 user-id etc. The user must use the IPC_CREAT flag or key = IPC_PRIVATE
828 to allocate a new segment.
829
830    If the segment already exists, the access permissions are verified,
831 and a check is made to see that it is not marked for destruction.
832
833    `size' is effectively rounded up to a multiple of PAGE_SIZE as shared
834 memory is allocated in pages.
835
836 Errors:
837 EINVAL : (allocate) Size not in range specified above.
838 (procure) Size greater than size of segment.
839 EEXIST : (allocate) IPC_CREAT | IPC_EXCL specified and resource exists.
840 EIDRM  : (procure) The resource is marked destroyed or was removed.
841 ENOSPC : (allocate) All id's are taken (max of SHMMNI id's system-wide).
842 Allocating a segment of the requested size would exceed the system wide
843 limit on total shared memory (SHMALL).
844 ENOENT : (procure) Resource does not exist and IPC_CREAT not specified.
845 EACCES : (procure) Do not have permission for specified access.
846 ENOMEM : (allocate) Could not allocate memory for shmid_ds or pg_table.
847
848 \1f
849 File: ipc.info,  Node: shmat,  Next: shmdt,  Prev: shmget,  Up: Shared Memory
850
851 1.7.2 shmat
852 -----------
853
854 Maps a shared segment into the process' address space.
855
856      char *virt_addr;
857      virt_addr =  shmat (int shmid, char *shmaddr, int shmflg);
858
859    * shmid : id got from call to shmget.
860
861    * shmaddr : requested attach address.
862      If shmaddr is 0 the system finds an unmapped region.
863      If a non-zero value is indicated the value must be page
864      aligned or the user must specify the SHM_RND flag.
865
866    * shmflg :
867      SHM_RDONLY : request read-only attach.
868      SHM_RND : attach address is rounded DOWN to a multiple of SHMLBA.
869
870    * returns: virtual address of attached segment. -1 on failure.
871
872    When shmaddr is 0, the attach address is determined by finding an
873 unmapped region in the address range 1G to 1.5G, starting at 1.5G and
874 coming down from there. The algorithm is very simple so you are
875 encouraged to avoid non-specific attaches.
876
877 Algorithm:
878      Determine attach address as described above.
879      Check region (shmaddr, shmaddr + size) is not mapped and allocate
880      page tables (undocumented SHM_REMAP flag!).
881      Map the region by setting up pointers into the internal page table.
882      Add a descriptor for the attach to the task struct for the process.
883      `shm_nattch', `shm_lpid', `shm_atime' are updated.
884
885 Notes:
886 The `brk' value is not altered.  The segment is automatically detached
887 when the process exits.  The same segment may be attached as read-only
888 or read-write and more than once in the process' address space.  A
889 shmat can succeed on a segment marked for destruction.  The request for
890 a particular type of attach is made using the SHM_RDONLY flag.  There
891 is no notion of a write-only attach. The requested attach permissions
892 must fall within those allowed by `shm_perm.mode'.
893
894 Errors:
895 EACCES : Do not have permission for requested access.
896 EINVAL : shmid < 0 or unused, shmaddr not aligned, attach at brk failed.
897 EIDRM  : resource was removed.
898 ENOMEM : Could not allocate memory for descriptor or page tables.
899
900 \1f
901 File: ipc.info,  Node: shmdt,  Next: shmctl,  Prev: shmat,  Up: Shared Memory
902
903 1.7.3 shmdt
904 -----------
905
906      int shmdt (char *shmaddr);
907
908    * shmaddr : attach address of segment (returned by shmat).
909
910    * returns : 0 on success. -1 on failure.
911
912    An attached segment is detached and `shm_nattch' decremented. The
913 occupied region in user space is unmapped. The segment is destroyed if
914 it is marked for destruction and `shm_nattch' is 0.  `shm_lpid' and
915 `shm_dtime' are updated.
916
917 Errors:
918 EINVAL : No shared memory segment attached at shmaddr.
919
920 \1f
921 File: ipc.info,  Node: shmctl,  Next: shmlimits,  Prev: shmdt,  Up: Shared Memory
922
923 1.7.4 shmctl
924 ------------
925
926 Destroys allocated segments. Reads/Writes the control structures.
927
928      int shmctl (int shmid, int cmd, struct shmid_ds *buf);
929
930    * shmid : id got from call to shmget.
931
932    * cmd : IPC_STAT, IPC_SET, IPC_RMID (*Note syscalls::).
933           IPC_SET : Used to set the owner uid, gid, and shm_perms.mode
934           field.
935
936           IPC_RMID : The segment is marked destroyed. It is only
937           destroyed on the last detach.
938
939           IPC_STAT : The shmid_ds structure is copied into the user
940           allocated buffer.
941
942    * buf : used to read (IPC_STAT) or write (IPC_SET) information.
943
944    * returns : 0 on success, -1 on failure.
945
946    The user must execute an IPC_RMID shmctl call to free the memory
947 allocated by the shared segment. Otherwise all the pages faulted in
948 will continue to live in memory or swap.
949
950 Errors:
951 EACCES : Do not have permission for requested access.
952 EFAULT : buf is not accessible.
953 EINVAL : shmid < 0 or unused.
954 EIDRM  : identifier destroyed.
955 EPERM  : not creator, owner or super-user (IPC_SET, IPC_RMID).
956
957 \1f
958 File: ipc.info,  Node: shmlimits,  Next: Notes,  Prev: shmctl,  Up: Shared Memory
959
960 1.7.5 Limits on Shared Memory Resources
961 ---------------------------------------
962
963 Limits:
964    * SHMMNI  max num of shared segments system wide ... 4096.
965
966    * SHMMAX  max shared memory segment size (bytes) ... 4M
967
968    * SHMMIN  min shared memory segment size (bytes).  1 byte (though
969      PAGE_SIZE is the effective minimum size).
970
971    * SHMALL  max shared mem system wide (in pages) ... policy.
972
973    * SHMLBA  segment low boundary address multiple.  Must be page
974      aligned. SHMLBA = PAGE_SIZE.
975    Unused or unimplemented:
976 SHMSEG : maximum number of shared segments per process.
977
978 \1f
979 File: ipc.info,  Node: Notes,  Next: Top,  Prev: shmlimits,  Up: Top
980
981 1.8 Miscellaneous Notes
982 =======================
983
984 The system calls are mapped into one - `sys_ipc'. This should be
985 transparent to the user.
986
987 1.8.1 Semaphore `undo' requests
988 -------------------------------
989
990 There is one sem_undo structure associated with a process for each
991 semaphore which was altered (with an undo request) by the process.
992 `sem_undo' structures are freed only when the process exits.
993
994    One major cause for unhappiness with the undo mechanism is that it
995 does not fit in with the notion of having an atomic set of operations
996 on an array. The undo requests for an array and each semaphore therein
997 may have been accumulated over many `semop' calls. Thus use the undo
998 mechanism with private semaphores only.
999
1000    Should the process sleep in `exit' or should all undo operations be
1001 applied with the IPC_NOWAIT flag in effect?  Currently  those undo
1002 operations which go through immediately are applied and those that
1003 require a wait are ignored silently.
1004
1005 1.8.2 Shared memory, `malloc' and the `brk'.
1006 --------------------------------------------
1007
1008 Note that since this section was written the implementation was changed
1009 so that non-specific attaches are done in the region 1G - 1.5G. However
1010 much of the following is still worth thinking about so I left it in.
1011
1012    On many systems, the shared memory is allocated in a special region
1013 of the address space ... way up somewhere. As mentioned earlier, this
1014 implementation attaches shared segments at the lowest possible address.
1015 Thus if you plan to use `malloc', it is wise to malloc a large space
1016 and then proceed to attach the shared segments. This way malloc sets
1017 the brk sufficiently above the region it will use.
1018
1019    Alternatively you can use `sbrk' to adjust the `brk' value as you
1020 make shared memory attaches. The implementation is not very smart about
1021 selecting attach addresses. Using the system default addresses will
1022 result in fragmentation if detaches do not occur in the reverse
1023 sequence as attaches.
1024
1025    Taking control of the matter is probably best. The rule applied is
1026 that attaches are allowed in unmapped regions other than in the text
1027 space (see <a.out.h>). Also remember that attach addresses and segment
1028 sizes are multiples of PAGE_SIZE.
1029
1030    One more trap (I quote Bruno on this). If you use malloc() to get
1031 space for your shared memory (ie. to fix the `brk'), you must ensure you
1032 get an unmapped address range. This means you must mallocate more memory
1033 than you had ever allocated before. Memory returned by malloc(), used,
1034 then freed by free() and then again returned by malloc is no good.
1035 Neither is calloced memory.
1036
1037    Note that a shared memory region remains a shared memory region until
1038 you unmap it. Attaching a segment at the `brk' and calling malloc after
1039 that will result in an overlap of what malloc thinks is its space with
1040 what is really a shared memory region. For example in the case of a
1041 read-only attach, you will not be able to write to the overlapped
1042 portion.
1043
1044 1.8.3 Fork, exec and exit
1045 -------------------------
1046
1047 On a fork, the child inherits attached shared memory segments but not
1048 the semaphore undo information.
1049
1050    In the case of an exec, the attached shared segments are detached.
1051 The sem undo information however remains intact.
1052
1053    Upon exit, all attached shared memory segments are detached.  The
1054 adjust values in the undo structures are added to the relevant semvals
1055 if the operations are permitted. Disallowed operations are ignored.
1056
1057 1.8.4 Other Features
1058 --------------------
1059
1060 These features of the current implementation are likely to be modified
1061 in the future.
1062
1063    The SHM_LOCK and SHM_UNLOCK flag are available (super-user) for use
1064 with the `shmctl' call to prevent swapping of a shared segment. The user
1065 must fault in any pages that are required to be present after locking
1066 is enabled.
1067
1068    The IPC_INFO, MSG_STAT, MSG_INFO, SHM_STAT, SHM_INFO, SEM_STAT,
1069 SEMINFO `ctl' calls are used by the `ipcs' program to provide
1070 information on allocated resources. These can be modified as needed or
1071 moved to a proc file system interface.
1072
1073
1074
1075
1076    Thanks to Ove Ewerlid, Bruno Haible, Ulrich Pegelow and Linus
1077 Torvalds for ideas, tutorials, bug reports and fixes, and merriment.
1078 And more thanks to Bruno.
1079
1080
1081 \1f
1082 Tag Table:
1083 Node: Top\7f469
1084 Node: Overview\7f1171
1085 Node: example\7f3013
1086 Node: perms\7f4490
1087 Node: syscalls\7f6055
1088 Node: Messages\7f9540
1089 Node: msgget\7f11580
1090 Node: msgsnd\7f12976
1091 Node: msgrcv\7f13956
1092 Node: msgctl\7f15667
1093 Node: msglimits\7f16887
1094 Node: Semaphores\7f17776
1095 Node: semget\7f19740
1096 Node: semop\7f21305
1097 Node: semctl\7f23881
1098 Node: semlimits\7f25651
1099 Node: Shared Memory\7f26805
1100 Node: shmget\7f28295
1101 Node: shmat\7f30102
1102 Node: shmdt\7f32151
1103 Node: shmctl\7f32696
1104 Node: shmlimits\7f33839
1105 Node: Notes\7f34502
1106 \1f
1107 End Tag Table