Tải bản đầy đủ - 0 (trang)
Chapter 6. I/O Multiplexing: The select and poll Functions

Chapter 6. I/O Multiplexing: The select and poll Functions

Tải bản đầy đủ - 0trang

Exercises

16.1



InourdiscussionofFigure16.10,wementionedthattheparentmustcallshutdown,

notclose.Why?



16.2



WhathappensinFigure16.10iftheserverprocessterminatesprematurely,plusthe

childreceivestheEOFandterminates,butthechilddoesnotnotifytheparent?



16.3



WhathappensinFigure16.10iftheparentdiesunexpectedlybeforethechild,and

thechildthenreadsanEOFonthesocket?



WhathappensinFigure16.11ifweremovethetwolines

16.4

if(n==0)

gotodone;/*connectcompletedimmediately*/



16.5



InSection16.3wesaidthatitispossiblefordatatoarriveforasocketbefore

connectreturns.Howcanthishappen?



6.5BatchInputandBuffering

Unfortunately,ourstr_clifunctionisstillnotcorrect.First,

let'sgobacktoouroriginalversion,Figure5.5.Itoperatesina

stop-and-waitmode,whichisfineforinteractiveuse:Itsendsa

linetotheserverandthenwaitsforthereply.Thisamountof

timeisoneRTTplustheserver'sprocessingtime(whichisclose

to0forasimpleechoserver).Wecanthereforeestimatehow

longitwilltakeforagivennumberoflinestobeechoedifwe

knowtheRTTbetweentheclientandserver.

ThepingprogramisaneasywaytomeasureRTTs.Ifwerun

pingtothehostconnix.comfromourhostsolaris,the

averageRTTover30measurementsis175ms.Page89of

TCPv1showsthatthesepingmeasurementsareforanIP

datagramwhoselengthis84bytes.Ifwetakethefirst2,000

linesoftheSolaristermcapfile,theresultingfilesizeis98,349

bytes,foranaverageof49bytesperline.Ifweaddthesizesof

theIPheader(20bytes)andtheTCPheader(20),theaverage

TCPsegmentwillbeabout89bytes,nearlythesameasthe

pingpacketsizes.Wecanthereforeestimatethatthetotal

clocktimewillbearound350secondsfor2,000lines

(2,000x0.175sec).IfwerunourTCPechoclientfromChapter

5,theactualtimeisabout354seconds,whichisverycloseto

ourestimate.

Ifweconsiderthenetworkbetweentheclientandserverasa

full-duplexpipe,withrequestsgoingfromtheclienttothe

serverandrepliesinthereversedirection,thenFigure6.10

showsourstop-and-waitmode.



Figure6.10.Timelineofstop-and-waitmode:

interactiveinput.



Arequestissentbytheclientattime0andweassumeanRTT

of8unitsoftime.Thereplysentattime4isreceivedattime7.

Wealsoassumethatthereisnoserverprocessingtimeand

thatthesizeoftherequestisthesameasthereply.Weshow

onlythedatapacketsbetweentheclientandserver,ignoring

theTCPacknowledgmentsthatarealsogoingacrossthe

network.

Sincethereisadelaybetweensendingapacketandthat

packetarrivingattheotherendofthepipe,andsincethepipe



isfull-duplex,inthisexample,weareonlyusingone-eighthof

thepipe'scapacity.Thisstop-and-waitmodeisfinefor

interactiveinput,butsinceourclientreadsfromstandardinput

andwritestostandardoutput,andsinceitistrivialunderthe

Unixshellstoredirecttheinputandoutput,wecaneasilyrun

ourclientinabatchmode.Whenweredirecttheinputand

output,however,theresultingoutputfileisalwayssmallerthan

theinputfile(andtheyshouldbeidenticalforanechoserver).

Toseewhat'shappening,realizethatinabatchmode,wecan

keepsendingrequestsasfastasthenetworkcanacceptthem.

Theserverprocessesthemandsendsbacktherepliesatthe

samerate.Thisleadstothefullpipeattime7,asshownin

Figure6.11.



Figure6.11.Fillingthepipebetweentheclient

andserver:batchmode.



Hereweassumethataftersendingthefirstrequest,we

immediatelysendanother,andthenanother.Wealsoassume

thatwecankeepsendingrequestsasfastasthenetworkcan

acceptthem,alongwithprocessingrepliesasfastasthe

networksuppliesthem.

TherearenumeroussubtletiesdealingwithTCP'sbulk

dataflowthatweareignoringhere,suchasitsslow-start

algorithm,whichlimitstherateatwhichdataissentona

neworidleconnection,andthereturningACKs.Theseare



allcoveredinChapter20ofTCPv1.

Toseetheproblemwithourrevisedstr_clifunctioninFigure

6.9,assumethattheinputfilecontainsonlyninelines.Thelast

lineissentattime8,asshowninFigure6.11.Butwecannot

closetheconnectionafterwritingthisrequestbecausethereare

stillotherrequestsandrepliesinthepipe.Thecauseofthe

problemisourhandlingofanEOFoninput:Thefunction

returnstothemainfunction,whichthenterminates.Butina

batchmode,anEOFoninputdoesnotimplythatwehave

finishedreadingfromthesocket;theremightstillberequests

onthewaytotheserver,orrepliesonthewaybackfromthe

server.

Whatweneedisawaytocloseone-halfoftheTCPconnection.

Thatis,wewanttosendaFINtotheserver,tellingitwehave

finishedsendingdata,butleavethesocketdescriptoropenfor

reading.Thisisdonewiththeshutdownfunction,whichis

describedinthenextsection.

Ingeneral,bufferingforperformanceaddscomplexitytoa

networkapplication,andthecodeinFigure6.9suffersfromthis

complexity.Considerthecasewhenseverallinesofinputare

availablefromthestandardinput.selectwillcausethecodeat

line20toreadtheinputusingfgetsandthat,inturn,willread

theavailablelinesintoabufferusedbystdio.But,fgetsonly

returnsasinglelineandleavesanyremainingdatasittingin

thestdiobuffer.Thecodeatline22ofFigure6.9writesthat

singlelinetotheserverandthenselectiscalledagaintowait

formorework,evenifthereareadditionallinestoconsumein

thestdiobuffer.Thereasonforthisisthatselectknows

nothingofthebuffersusedbystdioitwillonlyshowreadability

fromtheviewpointofthereadsystemcall,notcallslikefgets.

Forthisreason,mixingstdioandselectisconsideredvery

error-proneandshouldonlybedonewithgreatcare.

Thesameproblemexistswiththecalltoreadlineinthe



exampleinFigure6.9.Insteadofdatabeinghiddenfrom

selectinastdiobuffer,itishiddeninreadline'sbuffer.Recall

thatinSection3.9weprovidedafunctionthatgivesvisibility

intoreadline'sbuffer,soonepossiblesolutionistomodifyour

codetousethatfunctionbeforecallingselecttoseeifdata

hasalreadybeenreadbutnotconsumed.Butagain,the

complexitygrowsoutofhandquicklywhenwehavetohandle

thecasewherethereadlinebuffercontainsapartialline

(meaningwestillneedtoreadmore)aswellaswhenit

containsoneormorecompletelines(whichwecanconsume).

Wewilladdressthesebufferingconcernsintheimproved

versionofstr_clishowninSection6.7.



1.2ASimpleDaytimeClient

Let'sconsideraspecificexampletointroducemanyofthe

conceptsandtermsthatwewillencounterthroughoutthebook.

Figure1.5isanimplementationofaTCPtime-of-dayclient.

ThisclientestablishesaTCPconnectionwithaserverandthe

serversimplysendsbackthecurrenttimeanddateinahumanreadableformat.



Figure1.5TCPdaytimeclient.

intro/daytimetcpcli.c

1#include"unp.h"

2int

3main(intargc,char**argv)

4{

5intsockfd,n;

6charrecvline[MAXLINE+1];

7structsockaddr_inservaddr;

8if(argc!=2)

9err_quit("usage:a.out");

10if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)

11err_sys("socketerror");



12bzero(&servaddr,sizeof(servaddr));

13servaddr.sin_family=AF_INET;

14servaddr.sin_port=htons(13);/*daytimeserver*/

15if(inet_pton(AF_INET,argv[1],&servaddr.sin_addr)<=0

16err_quit("inet_ptonerrorfor%s",argv[1]);



17if(connect(sockfd,(SA*)&servaddr,sizeof(servaddr))

18err_sys("connecterror");

19while((n=read(sockfd,recvline,MAXLINE))>0){

20recvline[n]=0;/*nullterminate*/

21if(fputs(recvline,stdout)==EOF)

22err_sys("fputserror");

23}

24if(n<0)

25err_sys("readerror");

26exit(0);

27}

Thisistheformatthatwewilluseforallthesourcecode

inthetext.Eachnonblanklineisnumbered.Thetext

describingportionsofthecodenotesthestartingand

endinglinenumbersintheleftmargin,asshownshortly.

Sometimesaparagraphisprecededbyashort,

descriptive,boldheading,providingasummarystatement

ofthecodebeingdescribed.

Thehorizontalrulesatthebeginningandendofacode

fragmentspecifythesourcecodefilename:thefile

daytimetcpcli.cinthedirectoryintroforthisexample.

Sincethesourcecodeforalltheexamplesinthetextis

freelyavailable(seethePreface),thisletsyoulocatethe

appropriatesourcefile.Compiling,running,andespecially

modifyingtheseprogramswhilereadingthistextisan

excellentwaytolearntheconceptsofnetwork

programming.

Throughoutthetext,wewilluseindented,parenthetical

notessuchasthistodescribeimplementationdetailsand

historicalpoints.



Ifwecompiletheprogramintothedefaulta.outfileand

executeit,wewillhavethefollowingoutput:



solaris%a.out206.168.112.96



ourinput



MonMay2620:58:402003



theprogram'soutput



Wheneverwedisplayinteractiveinputandoutput,wewill

showourtypedinputinboldandthecomputeroutput

likethis.Commentsareaddedontherightsidein

italics.Wewillalwaysincludethenameofthesystemas

partoftheshellprompt(solarisinthisexample)to

showonwhichhostthecommandwasrun.Figure1.16

showsthesystemsusedtorunmostoftheexamplesin

thisbook.Thehostnamesusuallydescribetheoperating

system(OS)aswell.

Therearemanydetailstoconsiderinthis27-lineprogram.We

mentionthembrieflyhere,incasethisisyourfirstencounter

withanetworkprogram,andprovidemoreinformationon

thesetopicslaterinthetext.



Includeourownheader

1Weincludeourownheader,unp.h,whichwewillshowin

SectionD.1.Thisheaderincludesnumeroussystemheaders

thatareneededbymostnetworkprogramsanddefinesvarious

constantsthatweuse(e.g.,MAXLINE).



Command-linearguments

23Thisisthedefinitionofthemainfunctionalongwiththe



command-linearguments.Wehavewrittenthecodeinthistext

assuminganAmericanNationalStandardsInstitute(ANSI)C

compiler(alsoreferredtoasanISOCcompiler).



CreateTCPsocket

1011ThesocketfunctioncreatesanInternet(AF_INET)stream

(SOCK_STREAM)socket,whichisafancynameforaTCPsocket.

Thefunctionreturnsasmallintegerdescriptorthatwecanuse

toidentifythesocketinallfuturefunctioncalls(e.g.,thecalls

toconnectandreadthatfollow).

Theifstatementcontainsacalltothesocketfunction,

anassignmentofthereturnvaluetothevariablenamed

sockfd,andthenatestofwhetherthisassignedvalueis

lessthan0.WhilewecouldbreakthisintotwoC

statements,



sockfd=socket(AF_INET,SOCK_STREAM,0);

if(sockfd<0)

itisacommonCidiomtocombinethetwolines.Theset

ofparenthesesaroundthefunctioncallandassignmentis

required,giventheprecedencerulesofC(theless-than

operatorhasahigherprecedencethanassignment).Asa

matterofcodingstyle,theauthorsalwaysplaceaspace

betweenthetwoopeningparentheses,asavisual

indicatorthattheleft-handsideofthecomparisonisalso

anassignment.(ThisstyleiscopiedfromtheMinixsource

code[Tanenbaum1987].)Weusethissamestyleinthe

whilestatementlaterintheprogram.

Wewillencountermanydifferentusesoftheterm"socket."



First,theAPIthatweareusingiscalledthesocketsAPI.Inthe

precedingparagraph,wereferredtoafunctionnamedsocket

thatispartofthesocketsAPI.Intheprecedingparagraph,we

alsoreferredtoaTCPsocket,whichissynonymouswithaTCP

endpoint.

Ifthecalltosocketfails,weaborttheprogrambycallingour

ownerr_sysfunction.Itprintsourerrormessagealongwitha

descriptionofthesystemerrorthatoccurred(e.g.,"Protocol

notsupported"isonepossibleerrorfromsocket)and

terminatestheprocess.Thisfunction,andafewothersofour

ownthatbeginwitherr_,arecalledthroughoutthetext.We

willdescribetheminSectionD.3.



Specifyserver'sIPaddressandport

1216WefillinanInternetsocketaddressstructure(a

sockaddr_instructurenamedservaddr)withtheserver'sIP

addressandportnumber.Wesettheentirestructureto0using

bzero,settheaddressfamilytoAF_INET,settheportnumber

to13(whichisthewell-knownportofthedaytimeserveron

anyTCP/IPhostthatsupportsthisservice,asshowninFigure

2.18),andsettheIPaddresstothevaluespecifiedasthefirst

command-lineargument(argv[1]).TheIPaddressandport

numberfieldsinthisstructuremustbeinspecificformats:We

callthelibraryfunctionhtons("hosttonetworkshort")to

convertthebinaryportnumber,andwecallthelibraryfunction

inet_pton("presentationtonumeric")toconverttheASCII

command-lineargument(suchas206.62.226.35whenweran

thisexample)intotheproperformat.

bzeroisnotanANSICfunction.Itisderivedfromearly

Berkeleynetworkingcode.Nevertheless,weuseit

throughoutthetext,insteadoftheANSICmemset

function,becausebzeroiseasiertoremember(withonly



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 6. I/O Multiplexing: The select and poll Functions

Tải bản đầy đủ ngay(0 tr)

×