📄 ipc.texi
字号:
\input texinfo @c -*-texinfo-*-@comment %**start of header (This is for running Texinfo on a region.)@setfilename ipc.info@settitle Inter Process Communication.@setchapternewpage odd@comment %**end of header (This is for running Texinfo on a region.) @ifinfoThis file documents the System V style inter process communicationprimitives available under linux.Copyright @copyright{} 1992 krishna balasubramanian Permission is granted to use this material and the accompanyingprograms within the terms of the GNU GPL.@end ifinfo @titlepage@sp 10@center @titlefont{System V Inter Process Communication}@sp 2@center krishna balasubramanian, @comment The following two commands start the copyright page.@page@vskip 0pt plus 1filllCopyright @copyright{} 1992 krishna balasubramanian Permission is granted to use this material and the accompanyingprograms within the terms of the GNU GPL.@end titlepage@dircategory Miscellaneous@direntry* ipc: (ipc). System V style inter process communication@end direntry@node Top, Overview, Notes, (dir)@chapter System V IPC.These facilities are provided to maintain compatibility withprograms developed on system V unix systems and othersthat rely on these system V mechanisms to accomplish interprocess communication (IPC).@refillThe specifics described here are applicable to the Linux implementation.Other implementations may do things slightly differently.@menu* Overview:: What is system V ipc? Overall mechanisms.* Messages:: System calls for message passing.* Semaphores:: System calls for semaphores.* Shared Memory:: System calls for shared memory access.* Notes:: Miscellaneous notes.@end menu@node Overview, example, Top, Top@section Overview@noindent System V IPC consists of three mechanisms:@itemize @bullet@item Messages : exchange messages with any process or server.@item Semaphores : allow unrelated processes to synchronize execution.@item Shared memory : allow unrelated processes to share memory.@end itemize@menu* example:: Using shared memory.* perms:: Description of access permissions.* syscalls:: Overview of ipc system calls.@end menuAccess to all resources is permitted on the basis of permissionsset up when the resource was created.@refillA resource here consists of message queue, a semaphore set (array)or a shared memory segment.@refillA resource must first be allocated by a creator before it is used.The creator can assign a different owner. After use the resourcemust be explicitly destroyed by the creator or owner.@refillA resource is identified by a numeric @var{id}. Typically a creatordefines a @var{key} that may be used to access the resource. The userprocess may then use this @var{key} in the @dfn{get} system call to obtainthe @var{id} for the corresponding resource. This @var{id} is then used forall further access. A library call @dfn{ftok} is provided to translatepathnames or strings to numeric keys.@refillThere are system and implementation defined limits on the number andsizes of resources of any given type. Some of these are imposed by theimplementation and others by the system administratorwhen configuring the kernel (@xref{msglimits}, @xref{semlimits},@xref{shmlimits}).@refillThere is an @code{msqid_ds}, @code{semid_ds} or @code{shmid_ds} structassociated with each message queue, semaphore array or shared segment.Each ipc resource has an associated @code{ipc_perm} struct which definesthe creator, owner, access perms ..etc.., for the resource.These structures are detailed in the following sections.@refill@node example, perms, Overview, Overview@section exampleHere is a code fragment with pointers on how to use shared memory. Thesame methods are applicable to other resources.@refillIn a typical access sequence the creator allocates a new instanceof the resource with the @code{get} system call using the IPC_CREATflag.@refill@noindent creator process:@*@example#include <sys/shm.h>int id;key_t key;char proc_id = 'C'; int size = 0x5000; /* 20 K */int flags = 0664 | IPC_CREAT; /* read-only for others */key = ftok ("~creator/ipckey", proc_id);id = shmget (key, size, flags);exit (0); /* quit leaving resource allocated */@end example@noindentUsers then gain access to the resource using the same key.@*@noindentClient process:@example#include <sys/shm.h>char *shmaddr;int id;key_t key;char proc_id = 'C'; key = ftok ("~creator/ipckey", proc_id);id = shmget (key, 0, 004); /* default size */if (id == -1) perror ("shmget ..."); shmaddr = shmat (id, 0, SHM_RDONLY); /* attach segment for reading */if (shmaddr == (char *) -1) perror ("shmat ..."); local_var = *(shmaddr + 3); /* read segment etc. */shmdt (shmaddr); /* detach segment */@end example@noindentWhen the resource is no longer needed the creator should remove it.@*@noindentCreator/owner process 2:@examplekey = ftok ("~creator/ipckey", proc_id)id = shmget (key, 0, 0);shmctl (id, IPC_RMID, NULL);@end example@node perms, syscalls, example, Overview@section PermissionsEach resource has an associated @code{ipc_perm} struct which defines thecreator, owner and access perms for the resource.@refill@examplestruct ipc_perm key_t key; /* set by creator */ ushort uid; /* owner euid and egid */ ushort gid; ushort cuid; /* creator euid and egid */ ushort cgid; ushort mode; /* access modes in lower 9 bits */ ushort seq; /* sequence number */@end exampleThe creating process is the default owner. The owner can be reassignedby the creator and has creator perms. Only the owner, creator or super-usercan delete the resource.@refillThe lowest nine bits of the flags parameter supplied by the user to thesystem call are compared with the values stored in @code{ipc_perms.mode}to determine if the requested access is allowed. In the casethat the system call creates the resource, these bits are initializedfrom the user supplied value.@refillAs for files, access permissions are specified as read, write and execfor user, group or other (though the exec perms are unused). For example 0624 grants read-write to owner, write-only to group and read-onlyaccess to others.@refillFor shared memory, note that read-write access for segments is determinedby a separate flag which is not stored in the @code{mode} field.Shared memory segments attached with write access can be read.@refillThe @code{cuid}, @code{cgid}, @code{key} and @code{seq} fieldscannot be changed by the user.@refill@node syscalls, Messages, perms, Overview@section IPC system callsThis section provides an overview of the IPC system calls. See thespecific sections on each type of resource for details.@refillEach type of mechanism provides a @dfn{get}, @dfn{ctl} and one or more@dfn{op} system calls that allow the user to create or procure theresource (get), define its behaviour or destroy it (ctl) and manipulatethe resources (op).@refill @subsection The @dfn{get} system callsThe @code{get} call typically takes a @var{key} and returns a numeric@var{id} that is used for further access.The @var{id} is an index into the resource table. A sequencenumber is maintained and incremented when a resource isdestroyed so that access using an obsolete @var{id} is likely to fail.@refillThe user also specifies the permissions and other behaviourcharecteristics for the current access. The flags are or-ed with thepermissions when invoking system calls as in:@refill@examplemsgflg = IPC_CREAT | IPC_EXCL | 0666;id = msgget (key, msgflg);@end example@itemize @bullet@item@code{key} : IPC_PRIVATE => new instance of resource is initialized.@item@code{flags} :@itemize @asis@itemIPC_CREAT : resource created for @var{key} if it does not exist.@itemIPC_CREAT | IPC_EXCL : fail if resource exists for @var{key}.@end itemize@itemreturns : an identifier used for all further access to the resource.@end itemizeNote that IPC_PRIVATE is not a flag but a special @code{key}that ensures (when the call is successful) that a new resource iscreated.@refillUse of IPC_PRIVATE does not make the resource inaccessible to otherusers. For this you must set the access permissions appropriately.@refillThere is currently no way for a process to ensure exclusive access to aresource. IPC_CREAT | IPC_EXCL only ensures (on success) that a newresource was initialized. It does not imply exclusive access.@refill@noindentSee Also : @xref{msgget}, @xref{semget}, @xref{shmget}.@refill@subsection The @dfn{ctl} system callsProvides or alters the information stored in the structure that describesthe resource indexed by @var{id}.@refill@example#include <sys/msg.h>struct msqid_ds buf;err = msgctl (id, IPC_STAT, &buf);if (err) !$#%*else printf ("creator uid = %d\n", buf.msg_perm.cuid); ....@end example@noindentCommands supported by all @code{ctl} calls:@*@itemize @bullet@itemIPC_STAT : read info on resource specified by id into user allocatedbuffer. The user must have read access to the resource.@refill@itemIPC_SET : write info from buffer into resource data structure. Theuser must be owner creator or super-user.@refill@itemIPC_RMID : remove resource. The user must be the owner, creator orsuper-user.@refill@end itemizeThe IPC_RMID command results in immediate removal of a messagequeue or semaphore array. Shared memory segments however, areonly destroyed upon the last detach after IPC_RMID is executed.@refillThe @code{semctl} call provides a number of command options that allowthe user to determine or set the values of the semaphores in an array.@refill@noindentSee Also: @xref{msgctl}, @xref{semctl}, @xref{shmctl}.@refill@subsection The @dfn{op} system callsUsed to send or receive messages, read or alter semaphore values,attach or detach shared memory segments.The IPC_NOWAIT flag will cause the operation to fail with error EAGAINif the process has to wait on the call.@refill@noindent@code{flags} : IPC_NOWAIT => return with error if a wait is required.@noindentSee Also: @xref{msgsnd},@xref{msgrcv},@xref{semop},@xref{shmat},@xref{shmdt}.@refill@node Messages, msgget, syscalls, Top@section MessagesA message resource is described by a struct @code{msqid_ds} which isallocated and initialized when the resource is created. Some fieldsin @code{msqid_ds} can then be altered (if desired) by invoking @code{msgctl}.The memory used by the resource is released when it is destroyed bya @code{msgctl} call.@refill@examplestruct msqid_ds struct ipc_perm msg_perm; struct msg *msg_first; /* first message on queue (internal) */ struct msg *msg_last; /* last message in queue (internal) */ time_t msg_stime; /* last msgsnd time */ time_t msg_rtime; /* last msgrcv time */ time_t msg_ctime; /* last change time */ struct wait_queue *wwait; /* writers waiting (internal) */ struct wait_queue *rwait; /* readers waiting (internal) */ ushort msg_cbytes; /* number of bytes used on queue */ ushort msg_qnum; /* number of messages in queue */ ushort msg_qbytes; /* max number of bytes on queue */ ushort msg_lspid; /* pid of last msgsnd */ ushort msg_lrpid; /* pid of last msgrcv */@end exampleTo send or receive a message the user allocates a structure that lookslike a @code{msgbuf} but with an array @code{mtext} of the required size.Messages have a type (positive integer) associated with them so that(for example) a listener can choose to receive only messages of agiven type.@refill@examplestruct msgbuf long mtype; type of message (@xref{msgrcv}). char mtext[1]; message text .. why is this not a ptr?@end exampleThe user must have write permissions to send and read permissionsto receive messages on a queue.@refillWhen @code{msgsnd} is invoked, the user's message is copied intoan internal struct @code{msg} and added to the queue. A @code{msgrcv}will then read this message and free the associated struct @code{msg}.@refill@menu* msgget::* msgsnd::* msgrcv::* msgctl::* msglimits:: Implementation defined limits.@end menu@node msgget, msgsnd, Messages, Messages@subsection msgget@noindentA message queue is allocated by a msgget system call :@examplemsqid = msgget (key_t key, int msgflg);@end example@itemize @bullet@item@code{key}: an integer usually got from @code{ftok()} or IPC_PRIVATE.@refill@item@code{msgflg}:@itemize @asis@itemIPC_CREAT : used to create a new resource if it does not already exist.@itemIPC_EXCL | IPC_CREAT : used to ensure failure of the call if theresource already exists.@refill@itemrwxrwxrwx : access permissions.@end itemize@itemreturns: msqid (an integer used for all further access) on success.-1 on failure.@refill@end itemizeA message queue is allocated if there is no resource correspondingto the given key. The access permissions specified are then copiedinto the @code{msg_perm} struct and the fields in @code{msqid_ds}initialized. The user must use the IPC_CREAT flag or key = IPC_PRIVATE,if a new instance is to be allocated. If a resource corresponding to@var{key} already exists, the access permissions are verified.@refill@noindentErrors:@*@noindentEACCES : (procure) Do not have permission for requested access.@*@noindentEEXIST : (allocate) IPC_CREAT | IPC_EXCL specified and resource exists.@*@noindentEIDRM : (procure) The resource was removed.@*@noindentENOSPC : All id's are taken (max of MSGMNI id's system-wide).@*@noindentENOENT : Resource does not exist and IPC_CREAT not specified.@*@noindentENOMEM : A new @code{msqid_ds} was to be created but ... nomem.@node msgsnd, msgrcv, msgget, Messages@subsection msgsnd
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -