home *** CD-ROM | disk | FTP | other *** search
/ Chip 1995 March / CHIP3.mdf / slackwar / a / util / util-lin.2 / util-lin / util-linux-2.2 / sys-utils / ipc.info < prev    next >
Encoding:
GNU Info File  |  1995-02-22  |  38.0 KB  |  1,107 lines

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