1 This is ipc.info, produced by makeinfo version 4.7 from ipc.texi.
3 This file documents the System V style inter process communication
4 primitives available under linux.
6 Copyright (C) 1992 krishna balasubramanian
8 Permission is granted to use this material and the accompanying
9 programs within the terms of the GNU GPL.
11 INFO-DIR-SECTION Miscellaneous
13 * ipc: (ipc). System V style inter process communication
17 File: ipc.info, Node: Top, Next: Overview, Prev: Notes, Up: (dir)
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).
26 The specifics described here are applicable to the Linux
27 implementation. Other implementations may do things slightly
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.
39 File: ipc.info, Node: Overview, Next: example, Prev: Top, Up: Top
44 System V IPC consists of three mechanisms:
46 * Messages : exchange messages with any process or server.
48 * Semaphores : allow unrelated processes to synchronize execution.
50 * Shared memory : allow unrelated processes to share memory.
54 * example:: Using shared memory.
55 * perms:: Description of access permissions.
56 * syscalls:: Overview of ipc system calls.
58 Access to all resources is permitted on the basis of permissions set
59 up when the resource was created.
61 A resource here consists of message queue, a semaphore set (array)
62 or a shared memory segment.
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.
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
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::).
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.
87 File: ipc.info, Node: example, Next: perms, Prev: Overview, Up: Overview
92 Here is a code fragment with pointers on how to use shared memory. The
93 same methods are applicable to other resources.
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.
103 int size = 0x5000; /* 20 K */
104 int flags = 0664 | IPC_CREAT; /* read-only for others */
106 key = ftok ("~creator/ipckey", proc_id);
107 id = shmget (key, size, flags);
108 exit (0); /* quit leaving resource allocated */
110 Users then gain access to the resource using the same key.
118 key = ftok ("~creator/ipckey", proc_id);
120 id = shmget (key, 0, 004); /* default size */
122 perror ("shmget ...");
124 shmaddr = shmat (id, 0, SHM_RDONLY); /* attach segment for reading */
125 if (shmaddr == (char *) -1)
126 perror ("shmat ...");
128 local_var = *(shmaddr + 3); /* read segment etc. */
130 shmdt (shmaddr); /* detach segment */
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);
139 File: ipc.info, Node: perms, Next: syscalls, Prev: example, Up: Overview
144 Each resource has an associated `ipc_perm' struct which defines the
145 creator, owner and access perms for the resource.
148 key_t key; /* set by creator */
149 ushort uid; /* owner euid and egid */
151 ushort cuid; /* creator euid and egid */
153 ushort mode; /* access modes in lower 9 bits */
154 ushort seq; /* sequence number */
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.
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
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.
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.
175 The `cuid', `cgid', `key' and `seq' fields cannot be changed by the
179 File: ipc.info, Node: syscalls, Next: Messages, Prev: perms, Up: Overview
184 This section provides an overview of the IPC system calls. See the
185 specific sections on each type of resource for details.
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
192 1.4.1 The "get" system calls
193 ----------------------------
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.
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);
206 * `key' : IPC_PRIVATE => new instance of resource is initialized.
209 IPC_CREAT : resource created for KEY if it does not exist.
211 IPC_CREAT | IPC_EXCL : fail if resource exists for KEY.
213 * returns : an identifier used for all further access to the
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.
219 Use of IPC_PRIVATE does not make the resource inaccessible to other
220 users. For this you must set the access permissions appropriately.
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.
226 See Also : *Note msgget::, *Note semget::, *Note shmget::.
228 1.4.2 The "ctl" system calls
229 ----------------------------
231 Provides or alters the information stored in the structure that
232 describes the resource indexed by ID.
236 err = msgctl (id, IPC_STAT, &buf);
240 printf ("creator uid = %d\n", buf.msg_perm.cuid);
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.
247 * IPC_SET : write info from buffer into resource data structure. The
248 user must be owner creator or super-user.
250 * IPC_RMID : remove resource. The user must be the owner, creator or
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.
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.
260 See Also: *Note msgctl::, *Note semctl::, *Note shmctl::.
262 1.4.3 The "op" system calls
263 ---------------------------
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
270 `flags' : IPC_NOWAIT => return with error if a wait is required.
272 See Also: *Note msgsnd::,*Note msgrcv::,*Note semop::,*Note shmat::,
276 File: ipc.info, Node: Messages, Next: msgget, Prev: syscalls, Up: Top
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
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 */
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
309 long mtype; type of message (*Note msgrcv::).
310 char mtext[1]; message text .. why is this not a ptr?
312 The user must have write permissions to send and read permissions to
313 receive messages on a queue.
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'.
325 * msglimits:: Implementation defined limits.
328 File: ipc.info, Node: msgget, Next: msgsnd, Prev: Messages, Up: Messages
333 A message queue is allocated by a msgget system call :
335 msqid = msgget (key_t key, int msgflg);
337 * `key': an integer usually got from `ftok()' or IPC_PRIVATE.
340 IPC_CREAT : used to create a new resource if it does not
343 IPC_EXCL | IPC_CREAT : used to ensure failure of the call if
344 the resource already exists.
346 rwxrwxrwx : access permissions.
348 * returns: msqid (an integer used for all further access) on success.
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.
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.
367 File: ipc.info, Node: msgsnd, Next: msgrcv, Prev: msgget, Up: Messages
372 int msgsnd (int msqid, struct msgbuf *msgp, int msgsz, int msgflg);
374 * `msqid' : id obtained by a call to msgget.
376 * `msgsz' : size of msg text (`mtext') in bytes.
378 * `msgp' : message to be sent. (msgp->mtype must be positive).
380 * `msgflg' : IPC_NOWAIT.
382 * returns : msgsz on success. -1 on error.
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.
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.
397 File: ipc.info, Node: msgrcv, Next: msgctl, Prev: msgsnd, Up: Messages
402 int msgrcv (int msqid, struct msgbuf *msgp, int msgsz, long msgtyp,
405 * msqid : id obtained by a call to msgget.
407 * msgsz : maximum size of message to receive.
409 * msgp : allocated by user to store the message in.
412 0 => get first message on queue.
414 > 0 => get first message of matching type.
416 < 0 => get message with least type which is <= abs(msgtyp).
419 IPC_NOWAIT : Return immediately if message not found.
421 MSG_NOERROR : The message is truncated if it is larger than
424 MSG_EXCEPT : Used with msgtyp > 0 to receive any msg except
427 * returns : size of message if found. -1 on error.
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.
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.
437 The `msg_cbytes', `msg_qnum', `msg_lrpid', and `msg_rtime' fields
438 are updated. Writers waiting on the queue are awakened.
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.
450 File: ipc.info, Node: msgctl, Next: msglimits, Prev: msgrcv, Up: Messages
455 int msgctl (int msqid, int cmd, struct msqid_ds *buf);
457 * msqid : id obtained by a call to msgget.
459 * buf : allocated by user for reading/writing info.
461 * cmd : IPC_STAT, IPC_SET, IPC_RMID (*Note syscalls::).
463 IPC_STAT results in the copy of the queue data structure into the
464 user supplied buffer.
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.
470 Note that only the super user may increase the limit on the size of a
471 message queue beyond MSGMNB.
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.
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.
485 File: ipc.info, Node: msglimits, Next: Semaphores, Prev: msgctl, Up: Messages
487 1.5.5 Limis on Message Resources
488 --------------------------------
490 Sizeof various structures:
491 msqid_ds 52 /* 1 per message queue .. dynamic */
493 msg 16 /* 1 for each message in system .. dynamic */
495 msgbuf 8 /* allocated by user */
498 * MSGMNI : number of message queue identifiers ... policy.
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.
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
508 Unused or unimplemented:
509 MSGTQL max number of message headers system-wide.
510 MSGPOOL total size in bytes of msg pool.
513 File: ipc.info, Node: Semaphores, Next: semget, Prev: msglimits, Up: Top
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
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>.
529 Semaphore operations may also be qualified by a SEM_UNDO flag which
530 results in the operation being undone when the process exits.
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
538 A semaphore array is described by:
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 */
548 Each semaphore is described internally by :
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 */
560 * semlimits:: Limits imposed by this implementation.
563 File: ipc.info, Node: semget, Next: semop, Prev: Semaphores, Up: Semaphores
568 A semaphore array is allocated by a semget system call:
570 semid = semget (key_t key, int nsems, int semflg);
572 * `key' : an integer usually got from `ftok' or IPC_PRIVATE
575 # of semaphores in array (0 <= nsems <= SEMMSL <= SEMMNS)
577 0 => dont care can be used when not creating the resource.
578 If successful you always get access to the entire array
582 IPC_CREAT used to create a new resource
584 IPC_EXCL used with IPC_CREAT to ensure failure if the
587 rwxrwxrwx access permissions.
589 * returns : semid on success. -1 on failure.
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.
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
605 ENOENT : Resource does not exist and IPC_CREAT not specified.
606 EACCES : (procure) do not have permission for specified access.
609 File: ipc.info, Node: semop, Next: semctl, Prev: semget, Up: Semaphores
614 Operations on semaphore arrays are performed by calling semop :
616 int semop (int semid, struct sembuf *sops, unsigned nsops);
618 * semid : id obtained by a call to semget.
620 * sops : array of semaphore operations.
622 * nsops : number of operations in array (0 < nsops < SEMOPM).
624 * returns : semval for last operation. -1 on failure.
626 Operations are described by a structure sembuf:
628 ushort sem_num; /* semaphore index in array */
629 short sem_op; /* semaphore operation */
630 short sem_flg; /* operation flags */
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.
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.
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.
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.
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
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.
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
671 ERANGE : sem_op + semval > SEMVMX for some operation.
674 File: ipc.info, Node: semctl, Next: semlimits, Prev: semop, Up: Semaphores
679 int semctl (int semid, int semnum, int cmd, union semun arg);
681 * semid : id obtained by a call to semget.
684 GETPID return pid for the process that executed the last
687 GETVAL return semval of semaphore with index semnum.
689 GETNCNT return number of processes waiting for semval to
692 GETZCNT return number of processes waiting for semval to
695 SETVAL set semval = arg.val.
697 GETALL read all semval's into arg.array.
699 SETALL set all semval's with values given in arg.array.
701 * returns : 0 on success or as given above. -1 on failure.
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.
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
712 * IPC_SET, SETVAL, SETALL : sem_ctime is updated.
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.
718 * IPC_SET : sem_perm.uid, sem_perm.gid, sem_perm.mode are updated
719 from user supplied values.
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.
729 File: ipc.info, Node: semlimits, Next: Shared Memory, Prev: semctl, Up: Semaphores
731 1.6.4 Limits on Semaphore Resources
732 -----------------------------------
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 */
741 * SEMVMX 32767 semaphore maximum value (short).
743 * SEMMNI number of semaphore identifiers (or arrays) system
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 =
751 * SEMMNS maximum number of semaphores system wide ... policy.
752 Setting SEMMNS >= SEMMSL*SEMMNI makes it irrelevent.
754 * SEMOPM Maximum number of operations in one semop
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.
763 File: ipc.info, Node: Shared Memory, Next: shmget, Prev: semlimits, Up: Top
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.
774 A shared segment is described by :
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 */
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.
798 * shmlimits:: Limits imposed by this implementation.
801 File: ipc.info, Node: shmget, Next: shmat, Prev: Shared Memory, Up: Shared Memory
806 A shared memory segment is allocated by a shmget system call:
808 int shmget(key_t key, int size, int shmflg);
810 * key : an integer usually got from `ftok' or IPC_PRIVATE
812 * size : size of the segment in bytes (SHMMIN <= size <= SHMMAX).
815 IPC_CREAT used to create a new resource
817 IPC_EXCL used with IPC_CREAT to ensure failure if the
820 rwxrwxrwx access permissions.
822 * returns : shmid on success. -1 on failure.
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.
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.
833 `size' is effectively rounded up to a multiple of PAGE_SIZE as shared
834 memory is allocated in pages.
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.
849 File: ipc.info, Node: shmat, Next: shmdt, Prev: shmget, Up: Shared Memory
854 Maps a shared segment into the process' address space.
857 virt_addr = shmat (int shmid, char *shmaddr, int shmflg);
859 * shmid : id got from call to shmget.
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.
867 SHM_RDONLY : request read-only attach.
868 SHM_RND : attach address is rounded DOWN to a multiple of SHMLBA.
870 * returns: virtual address of attached segment. -1 on failure.
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.
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.
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'.
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.
901 File: ipc.info, Node: shmdt, Next: shmctl, Prev: shmat, Up: Shared Memory
906 int shmdt (char *shmaddr);
908 * shmaddr : attach address of segment (returned by shmat).
910 * returns : 0 on success. -1 on failure.
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.
918 EINVAL : No shared memory segment attached at shmaddr.
921 File: ipc.info, Node: shmctl, Next: shmlimits, Prev: shmdt, Up: Shared Memory
926 Destroys allocated segments. Reads/Writes the control structures.
928 int shmctl (int shmid, int cmd, struct shmid_ds *buf);
930 * shmid : id got from call to shmget.
932 * cmd : IPC_STAT, IPC_SET, IPC_RMID (*Note syscalls::).
933 IPC_SET : Used to set the owner uid, gid, and shm_perms.mode
936 IPC_RMID : The segment is marked destroyed. It is only
937 destroyed on the last detach.
939 IPC_STAT : The shmid_ds structure is copied into the user
942 * buf : used to read (IPC_STAT) or write (IPC_SET) information.
944 * returns : 0 on success, -1 on failure.
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.
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).
958 File: ipc.info, Node: shmlimits, Next: Notes, Prev: shmctl, Up: Shared Memory
960 1.7.5 Limits on Shared Memory Resources
961 ---------------------------------------
964 * SHMMNI max num of shared segments system wide ... 4096.
966 * SHMMAX max shared memory segment size (bytes) ... 4M
968 * SHMMIN min shared memory segment size (bytes). 1 byte (though
969 PAGE_SIZE is the effective minimum size).
971 * SHMALL max shared mem system wide (in pages) ... policy.
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.
979 File: ipc.info, Node: Notes, Next: Top, Prev: shmlimits, Up: Top
981 1.8 Miscellaneous Notes
982 =======================
984 The system calls are mapped into one - `sys_ipc'. This should be
985 transparent to the user.
987 1.8.1 Semaphore `undo' requests
988 -------------------------------
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.
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.
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.
1005 1.8.2 Shared memory, `malloc' and the `brk'.
1006 --------------------------------------------
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.
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.
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.
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.
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.
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
1044 1.8.3 Fork, exec and exit
1045 -------------------------
1047 On a fork, the child inherits attached shared memory segments but not
1048 the semaphore undo information.
1050 In the case of an exec, the attached shared segments are detached.
1051 The sem undo information however remains intact.
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.
1057 1.8.4 Other Features
1058 --------------------
1060 These features of the current implementation are likely to be modified
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
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.
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.
1084 Node: Overview
\7f1171
1085 Node: example
\7f3013
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
1097 Node: semctl
\7f23881
1098 Node: semlimits
\7f25651
1099 Node: Shared Memory
\7f26805
1100 Node: shmget
\7f28295
1103 Node: shmctl
\7f32696
1104 Node: shmlimits
\7f33839