📄 tutor.me
字号:
.\" Copyright (c) 1986, 1993.\" The Regents of the University of California. All rights reserved..\".\" Redistribution and use in source and binary forms, with or without.\" modification, are permitted provided that the following conditions.\" are met:.\" 1. Redistributions of source code must retain the above copyright.\" notice, this list of conditions and the following disclaimer..\" 2. Redistributions in binary form must reproduce the above copyright.\" notice, this list of conditions and the following disclaimer in the.\" documentation and/or other materials provided with the distribution..\" 3. All advertising materials mentioning features or use of this software.\" must display the following acknowledgement:.\" This product includes software developed by the University of.\" California, Berkeley and its contributors..\" 4. Neither the name of the University nor the names of its contributors.\" may be used to endorse or promote products derived from this software.\" without specific prior written permission..\".\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION).\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF.\" SUCH DAMAGE..\".\" @(#)tutor.me 8.1 (Berkeley) 8/14/93.\".oh 'Introductory 4.4BSD IPC''PSD:20-%'.eh 'PSD:20-%''Introductory 4.4BSD IPC'.rs.sp 2.sz 14.ft B.ce 2An Introductory 4.4BSDInterprocess Communication Tutorial.sz 10.sp 2.ce.i "Stuart Sechrest".ft.sp.ce 4Computer Science Research GroupComputer Science DivisionDepartment of Electrical Engineering and Computer ScienceUniversity of California, Berkeley.sp 2.ce.i ABSTRACT.sp.(c.ppBerkeley UNIX\(dg 4.4BSD offers several choices for interprocess communication.To aid the programmer in developing programs which are comprised ofcooperatingprocesses, the different choices are discussed and a series of example programs are presented. These programsdemonstrate in a simple way the use of pipes, socketpairs, socketsand the use of datagram and stream communication. The intent of thisdocument is to present a few simple example programs, not to describe thenetworking system in full..)c.sp 2.(f\(dg\|UNIX is a trademark of AT&T Bell Laboratories..)f.b.sh 1 "Goals".r.ppFacilities for interprocess communication (IPC) and networkingwere a major addition to UNIX in the Berkeley UNIX 4.2BSD release.These facilities required major additions and some changesto the system interface.The basic idea of this interface is to make IPC similar to file I/O.In UNIX a process has a set of I/O descriptors, from which one readsand to which one writes.Descriptors may refer to normal files, to devices (including terminals),or to communication channels.The use of a descriptor has three phases: its creation,its use for reading and writing, and its destruction. By using descriptorsto write files, rather than simply naming the target file in the writecall, one gains a surprising amount of flexibility. Often, the program thatcreates a descriptor will be different from the program that uses thedescriptor. For example the shell can create a descriptor for the output of the `ls'command that will cause the listing to appear in a file rather thanon a terminal.Pipes are another form of descriptor that have been used in UNIXfor some time.Pipes allow one-way data transmission from one processto another; the two processes and the pipe must be set up by a commonancestor..ppThe use of descriptors is not the only communication interfaceprovided by UNIX.The signal mechanism sends a tiny amount of information from one process to another.The signaled process receives only the signal type,not the identity of the sender,and the number of possible signals is small.The signal semantics limit the flexibility of the signaling mechanismas a means of interprocess communication..ppThe identification of IPC with I/O is quite longstanding in UNIX andhas proved quite successful. At first, however, IPC was limited toprocesses communicating within a single machine. With Berkeley UNIX4.2BSD this expanded to include IPC between machines. This expansionhas necessitated some change in the way that descriptors are created.Additionally, new possibilities for the meaning of read and write havebeen admitted. Originally the meanings, or semantics, of these termswere fairly simple. When you wrote something it was delivered. Whenyou read something, you were blocked until the data arrived.Other possibilities exist,however. One can write without full assurance of delivery if one cancheck later to catch occasional failures. Messages can be kept asdiscrete units or merged into a stream. One can ask to read, but insist on not waiting if nothing is immediatelyavailable. These new possibilities are allowed in the Berkeley UNIX IPCinterface. .ppThus Berkeley UNIX 4.4BSD offers several choices for IPC.This paper presents simple examples that illustrate some ofthe choices.The reader is presumed to be familiar with the C programming language[Kernighan & Ritchie 1978],but not necessarily with the system calls of the UNIX system or withprocesses and interprocess communication.The paper reviews the notion of a process and the types ofcommunication that are supported by Berkeley UNIX 4.4BSD.A series of examples are presented that create processes that communicatewith one another. The programs show different ways of establishingchannels of communication.Finally, the calls that actually transfer data are reviewed.To clearly present how communication can take place,the example programs have been cleared of anything thatmight be construed as useful work.They can, therefore, serve as modelsfor the programmer trying to construct programs which are comprised of cooperating processes..b.sh 1 "Processes".ppA \fIprogram\fP is both a sequence of statements and a rough way of referring to the computation that occurs when the compiled statements are run.A \fIprocess\fP can be thought of as a single line of control in a program.Most programs execute some statements, go through a few loops, branch invarious directions and then end. These are single process programs.Programs can also have a point where control splits into two independent lines,an action called \fIforking.\fPIn UNIX these lines can never join again. A call to the system routine \fIfork()\fP, causes a process to split in this way.The result of this call is that two independent processes will berunning, executing exactly the same code.Memory values will be the same for all values set before the fork, but,subsequently, each version will be able to change only the value of its own copy of each variable.Initially, the only difference between the two will be the value returned by\fIfork().\fP The parent will receive a process id for the child, the child will receive a zero.Calls to \fIfork(),\fPtherefore, typically precede, or are included in, an if-statement..ppA process views the rest of the system through a private table of descriptors.The descriptors can represent open files or sockets (sockets are communicationobjects that will be discussed below). Descriptors are referred toby their index numbers in the table. The first three descriptors are oftenknown by special names, \fI stdin, stdout\fP and \fIstderr\fP.These are the standard input, output and error.When a process forks, its descriptor table is copied to the child.Thus, if the parent's standard input is being taken from a terminal(devices are also treated as files in UNIX), the child's input will be taken from thesame terminal. Whoever reads first will get the input. If, before forking,the parent changes its standard input so that it is reading from anew file, the child will take its input from the new file. It isalso possible to take input from a socket, rather than from a file..b.sh 1 "Pipes".r.ppMost users of UNIX know that they can pipe the output of a program ``prog1'' to the input of another, ``prog2,'' by typing the command\fI``prog1 | prog2.''\fPThis is called ``piping'' the output of one programto another because the mechanism used to transfer the output is called apipe.When the user types a command, the command is read by the shell, whichdecides how to execute it. If the command is simple, for example,.i "``prog1,''"the shell forks a process, which executes the program, prog1, and then dies.The shell waits for this termination and then prompts for the nextcommand.If the command is a compound command,.i "``prog1 | prog2,''"the shell creates two processes connected by a pipe. One processruns the program, prog1, the other runs prog2. The pipe is an I/Omechanism with two ends, or sockets. Data that is written into one socketcan be read from the other. .(z.ft CW.so pipe.c.ft.ce 1Figure 1\ \ Use of a pipe.)z.ppSince a program specifies its input and output only by the descriptor tableindices, which appear as variables or constants,the input source and output destination can be changed withoutchanging the text of the program.It is in this way that the shell is able to set up pipes. Before executingprog1, the process can close whatever is at \fIstdout\fPand replace it with oneend of a pipe. Similarly, the process that will execute prog2 can substitutethe opposite end of the pipe for \fIstdin.\fP.ppLet us now examine a program that creates a pipe for communication betweenits child and itself (Figure 1).A pipe is created by a parent process, which then forks.When a process forks, the parent's descriptor table is copied into the child's. .ppIn Figure 1, the parent process makes a call to the system routine \fIpipe().\fPThis routine creates a pipe and places descriptors for the socketsfor the two ends of the pipe in the process's descriptor table.\fIPipe()\fPis passed an array into which it places the index numbers of the sockets it created.The two ends are not equivalent. The socket whose index isreturned in the low word of the array is opened for reading only,while the socket in the high end is opened only for writing.This corresponds to the fact that the standard input is the firstdescriptor of a process's descriptor table and the standard outputis the second. After creating the pipe, the parent creates the child with which it will share the pipe by calling \fIfork().\fPFigure 2 illustrates the effect of a fork.The parent process's descriptor table points to both ends of the pipe.After the fork, both parent's and child's descriptor tables point tothe pipe.The child can then use the pipe to send a message to the parent..(z.so fig2.pic.ce 2Figure 2\ \ Sharing a pipe between parent and child.ce 0.)z.ppJust what is a pipe?It is a one-way communication mechanism, with one end openedfor reading and the other end for writing.Therefore, parent and child need to agree on which way to turnthe pipe, from parent to child or the other way around.Using the same pipe for communication both from parent to child and from child to parent would be possible (since both processes have references to both ends), but very complicated.If the parent and child are to have a two-way conversation,the parent creates two pipes, one for use in each direction.(In accordance with their plans, both parent and child in the example aboveclose the socket that they will not use. It is not required that unuseddescriptors be closed, but it is good practice.)A pipe is also a \fIstream\fP communication mechanism; thatis, all messages sent through the pipe are placed in orderand reliably delivered. When the reader asks for a certainnumber of bytes from thisstream, he is given as many bytes as are available, upto the amount of the request. Note that these bytes may have come from the same call to \fIwrite()\fR or from several calls to \fIwrite()\fRwhich were concatenated..b.sh 1 "Socketpairs".r.ppBerkeley UNIX 4.4BSD provides a slight generalization of pipes. A pipe is apair of connected sockets for one-way stream communication. One mayobtain a pair of connected sockets for two-way stream communicationby calling the routine \fIsocketpair().\fPThe program in Figure 3 calls \fIsocketpair()\fPto create such a connection. The program uses the link forcommunication in both directions. Since socketpairs arean extension of pipes, their use resembles that of pipes. Figure 4 illustrates the result of a fork following a call to \fIsocketpair().\fP.pp\fISocketpair()\fPtakes asarguments a specification of a domain, a style of communication, and aprotocol. These are the parameters shown in the example.Domains and protocols will be discussed in the next section.Briefly,a domain is a space of names that may be boundto sockets and implies certain other conventions.Currently, socketpairs have only been implemented for onedomain, called the UNIX domain.The UNIX domain uses UNIX path names for naming sockets. It only allows communicationbetween sockets on the same machine..ppNote that the header files .i "<sys/socket.h>"and.i "<sys/types.h>."are required in this program.The constants AF_UNIX and SOCK_STREAM are defined in
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -