BSD进程间通信编程入门,主要讲socket编程.pdf

上传人:asd****56 文档编号:70323078 上传时间:2023-01-19 格式:PDF 页数:23 大小:52.37KB
返回 下载 相关 举报
BSD进程间通信编程入门,主要讲socket编程.pdf_第1页
第1页 / 共23页
BSD进程间通信编程入门,主要讲socket编程.pdf_第2页
第2页 / 共23页
点击查看更多>>
资源描述

《BSD进程间通信编程入门,主要讲socket编程.pdf》由会员分享,可在线阅读,更多相关《BSD进程间通信编程入门,主要讲socket编程.pdf(23页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、Introductory 4.4BSD IPCPSD:20-1An Introductory 4.4BSDInterprocess Communication TutorialStuart SechrestComputer Science Research GroupComputer Science DivisionDepartment of Electrical Engineering and Computer ScienceUniversity of California,BerkeleyABSTRACTBerkeley UNIX 4.4BSD offers several choices

2、 for interprocess communication.To aid the pro-grammer in developing programs which are comprised of cooperating processes,the different choices arediscussed and a series of example programs are presented.These programs demonstrate in a simple waythe use of pipes,socketpairs,sockets and the use of d

3、atagram and stream communication.The intent of thisdocument is to present a few simple example programs,not to describe the networking system in full.1.GoalsFacilities for interprocess communication(IPC)and networking were a major addition to UNIX inthe Berkeley UNIX 4.2BSD release.These facilities

4、required major additions and some changes to the sys-tem interface.The basic idea of this interface is to make IPC similar to file I/O.In UNIX a process has aset of I/O descriptors,from which one reads and to which one writes.Descriptors may refer to normal files,to devices(including terminals),or t

5、o communication channels.The use of a descriptor has three phases:its creation,its use for reading and writing,and its destruction.By using descriptors to write files,ratherthan simply naming the target file in the write call,one gains a surprising amount of flexibility.Often,theprogram that creates

6、 a descriptor will be different from the program that uses the descriptor.For examplethe shell can create a descriptor for the output of the ls command that will cause the listing to appear in afile rather than on a terminal.Pipes are another form of descriptor that have been used in UNIX for someti

7、me.Pipes allow one-way data transmission from one process to another;the two processes and the pipemust be set up by a common ancestor.The use of descriptors is not the only communication interface provided by UNIX.The signal mech-anism sends a tiny amount of information from one process to another.

8、The signaled process receives onlythe signal type,not the identity of the sender,and the number of possible signals is small.The signalsemantics limit the flexibility of the signaling mechanism as a means of interprocess communication.The identification of IPC with I/O is quite longstanding in UNIX

9、and has proved quite successful.Atfirst,however,IPC was limited to processes communicating within a single machine.With Berkeley UNIX4.2BSD this expanded to include IPC between machines.This expansion has necessitated some change inthe way that descriptors are created.Additionally,new possibilities

10、for the meaning of read and write havebeen admitted.Originally the meanings,or semantics,of these terms were fairly simple.When you wrotesomething it was delivered.When you read something,you were blocked until the data arrived.Other pos-sibilities exist,however.One can write without full assurance

11、of delivery if one can check later to catchoccasional failures.Messages can be kept as discrete units or merged into a stream.One can ask to read,UNIX is a trademark of AT&T Bell Laboratories.PSD:20-2 Introductory 4.4BSD IPCbut insist on not waiting if nothing is immediately available.These new poss

12、ibilities are allowed in theBerkeley UNIX IPC interface.Thus Berkeley UNIX 4.4BSD offers several choices for IPC.This paper presents simple examplesthat illustrate some of the choices.The reader is presumed to be familiar with the C programming languageKernighan&Ritchie 1978,but not necessarily with

13、 the system calls of the UNIX system or with pro-cesses and interprocess communication.The paper reviews the notion of a process and the types of com-munication that are supported by Berkeley UNIX 4.4BSD.A series of examples are presented that createprocesses that communicate with one another.The pr

14、ograms show different ways of establishing channelsof communication.Finally,the calls that actually transfer data are reviewed.To clearly present how com-munication can take place,the example programs have been cleared of anything that might be construed asuseful work.They can,therefore,serve as mod

15、els for the programmer trying to construct programs whichare comprised of cooperating processes.2.ProcessesA program is both a sequence of statements and a rough way of referring to the computation thatoccurs when the compiled statements are run.A process can be thought of as a single line of contro

16、l in aprogram.Most programs execute some statements,go through a few loops,branch in various directionsand then end.These are single process programs.Programs can also have a point where control splits intotwo independent lines,an action called forking.In UNIX these lines can never join again.A call

17、 to thesystem routine fork(),causes a process to split in this way.The result of this call is that two independentprocesses will be running,executing exactly the same code.Memory values will be the same for all valuesset before the fork,but,subsequently,each version will be able to change only the v

18、alue of its own copy ofeach variable.Initially,the only difference between the two will be the value returned by fork().The par-ent will receive a process id for the child,the child will receive a zero.Calls to fork(),therefore,typicallyprecede,or are included in,an if-statement.A process views the

19、rest of the system through a private table of descriptors.The descriptors can rep-resent open files or sockets(sockets are communication objects that will be discussed below).Descriptorsare referred to by their index numbers in the table.The first three descriptors are often known by specialnames,st

20、din,stdout and stderr.These are the standard input,output and error.When a process forks,itsdescriptor table is copied to the child.Thus,if the parents standard input is being taken from a terminal(devices are also treated as files in UNIX),the childs input will be taken from the same terminal.Whoev

21、erreads first will get the input.If,before forking,the parent changes its standard input so that it is readingfrom a new file,the child will take its input from the new file.It is also possible to take input from a socket,rather than from a file.3.PipesMost users of UNIX know that they can pipe the

22、output of a program prog1 to the input ofanother,prog2,by typing the command prog1|pro g2.This is called piping the output of one pro-gram to another because the mechanism used to transfer the output is called a pipe.When the user types acommand,the command is read by the shell,which decides how to

23、execute it.If the command is simple,for example,prog1,the shell forks a process,which executes the program,prog1,and then dies.Theshell waits for this termination and then prompts for the next command.If the command is a compoundcommand,prog1|pro g2,the shell creates two processes connected by a pip

24、e.One process runs the pro-gram,prog1,the other runs prog2.The pipe is an I/O mechanism with two ends,or sockets.Data that iswritten into one socket can be read from the other.Since a program specifies its input and output only by the descriptor table indices,which appear asvariables or constants,th

25、e input source and output destination can be changed without changing the text ofthe program.It is in this way that the shell is able to set up pipes.Before executing prog1,the process canclose whatever is at stdout and replace it with one end of a pipe.Similarly,the process that will executeprog2 c

26、an substitute the opposite end of the pipe for stdin.Introductory 4.4BSD IPCPSD:20-3#include#define DATA Bright star,would I were steadfast as thou art./*This program creates a pipe,then forks.The child communicates to the*parent over the pipe.Notice that a pipe is a one-way communications*device.I

27、can write to the output socket(sockets1,the second socket*of the array returned by pipe()and read from the input socket*(sockets0),but not vice versa.*/main()int sockets2,child;/*Create a pipe*/if(pipe(sockets)0)perror(opening stream socket pair);exit(10);if(child=fork()=-1)perror(fork);else if(chil

28、d)char buf1024;/*This is still the parent.It reads the childs message.*/close(sockets1);if(read(sockets0,buf,1024)%sn,buf);close(sockets0);else/*This is the child.It writes a message to its parent.*/close(sockets0);if(write(sockets1,DATA,sizeof(DATA)0)perror(writing message);close(sockets1);Figure 1

29、 Use of a pipeLet us now examine a program that creates a pipe for communication between its child and itself(Figure 1).A pipe is created by a parent process,which then forks.When a process forks,the parentsdescriptor table is copied into the childs.In Figure 1,the parent process makes a call to the

30、 system routine pipe().This routine creates a pipeand places descriptors for the sockets for the two ends of the pipe in the processs descriptor table.Pipe()ispassed an array into which it places the index numbers of the sockets it created.The two ends are notequivalent.The socket whose index is ret

31、urned 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 standardinput is the first descriptor of a processs descriptor table and the standard output is the second.AfterPSD:20-4 Introductory 4.4BSD

32、 IPCcreating the pipe,the parent creates the child with which it will share the pipe by calling fork().Figure 2illustrates the effect of a fork.The parent processs descriptor table points to both ends of the pipe.Afterthe fork,both parents and childs descriptor tables point to the pipe.The child can

33、 then use the pipe tosend a message to the parent.Just what is a pipe?It is a one-way communication mechanism,with one end opened for reading andthe other end for writing.Therefore,parent and child need to agree on which way to turn the pipe,fromparent to child or the other way around.Using the same

34、 pipe for communication both from parent to childand from child to parent would be possible(since both processes have references to both ends),but verycomplicated.If the parent and child are to have a two-way conversation,the parent creates two pipes,onefor use in each direction.(In accordance with

35、their plans,both parent and child in the example above closethe socket that they will not use.It is not required that unused descriptors be closed,but it is good prac-tice.)A pipe is also a stream communication mechanism;that is,all messages sent through the pipe areChildParentParentPIPEPIPEFigure 2

36、 Sharing a pipe between parent and childIntroductory 4.4BSD IPCPSD:20-5placed in order and reliably delivered.When the reader asks for a certain number of bytes from this stream,he is given as many bytes as are available,up to the amount of the request.Note that these bytes may havecome from the sam

37、e call to write()or from several calls to write()which were concatenated.4.SocketpairsBerkeley UNIX 4.4BSD provides a slight generalization of pipes.A pipe is a pair of connected sock-ets for one-way stream communication.One may obtain a pair of connected sockets for two-way streamcommunication by c

38、alling the routine socketpair().The program in Figure 3 calls socketpair()to createsuch a connection.The program uses the link for communication in both directions.Since socketpairs arean extension of pipes,their use resembles that of pipes.Figure 4 illustrates the result of a fork following acall t

39、o socketpair().Socketpair()takes as arguments a specification of a domain,a style of communication,and a proto-col.These are the parameters shown in the example.Domains and protocols will be discussed in the nextsection.Briefly,a domain is a space of names that may be bound to sockets and implies ce

40、rtain other con-ventions.Currently,socketpairs have only been implemented for one domain,called the UNIX domain.The UNIX domain uses UNIX path names for naming sockets.It only allows communication betweensockets on the same machine.Note that the header files and.are required in this program.The con-

41、stants AF_UNIX and SOCK_STREAM are defined in,which in turn requires the file for some of its definitions.5.Domains and ProtocolsPipes and socketpairs are a simple solution for communicating between a parent and child or betweenchild processes.What if we wanted to have processes that have no common

42、ancestor with whom to set upcommunication?Neither standard UNIX pipes nor socketpairs are the answer here,since both mechanismsrequire a common ancestor to set up the communication.We would like to hav e two processes separatelycreate sockets and then have messages sent between them.This is often th

43、e case when providing or using aservice in the system.This is also the case when the communicating processes are on separate machines.In Berkeley UNIX 4.4BSD one can create individual sockets,give them names and send messages betweenthem.Sockets created by different programs use names to refer to on

44、e another;names generally must betranslated into addresses for use.The space from which an address is drawn is referred to as a domain.There are several domains for sockets.Two that will be used in the examples here are the UNIX domain(or AF_UNIX,for Address Format UNIX)and the Internet domain(or AF

45、_INET).UNIX domain IPC isan experimental facility in 4.2BSD and 4.3BSD.In the UNIX domain,a socket is given a path name withinthe file system name space.A file system node is created for the socket and other processes may then referto the socket by giving the proper pathname.UNIX domain names,theref

46、ore,allow communicationbetween any two processes that work in the same file system.The Internet domain is the UNIX implemen-tation of the DARPA Internet standard protocols IP/TCP/UDP.Addresses in the Internet domain consist ofa machine network address and an identifying number,called a port.Internet

47、 domain names allow commu-nication between machines.Communication follows some particular style.Currently,communication is either through astream or by datagram.Stream communication implies several things.Communication takes place acrossa connection between two sockets.The communication is reliable,

48、error-free,and,as in pipes,no messageboundaries are kept.Reading from a stream may result in reading the data sent from one or several calls towrite()or only part of the data from a single call,if there is not enough room for the entire message,or ifnot all the data from a large message has been tra

49、nsferred.The protocol implementing such a style willretransmit messages received with errors.It will also return error messages if one tries to send a messageafter the connection has been broken.Datagram communication does not use connections.Each messageis addressed individually.If the address is c

50、orrect,it will generally be received,although this is not guaran-teed.Often datagrams are used for requests that require a response from the recipient.If no responsePSD:20-6 Introductory 4.4BSD IPC#include#include#include#define DATA1 In Xanadu,did Kublai Khan.#define DATA2 A stately pleasure dome d

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 技术资料 > 其他杂项

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁