Serial Communications in Win32.docx
- 文档编号:12369190
- 上传时间:2023-04-18
- 格式:DOCX
- 页数:43
- 大小:37.71KB
Serial Communications in Win32.docx
《Serial Communications in Win32.docx》由会员分享,可在线阅读,更多相关《Serial Communications in Win32.docx(43页珍藏版)》请在冰豆网上搜索。
SerialCommunicationsinWin32
SerialCommunicationsinWin32
AllenDenver
MicrosoftWindowsDeveloperSupport
December11,1995
Allenseldomeatsbreakfast,butifhehadtopickafavorite,Win32serialcommunicationswouldbethetopchoice.
Abstract
SerialcommunicationsinMicrosoft®Win32®issignificantlydifferentfromserialcommunicationsin16-bitMicrosoftWindows®.Thosefamiliarwith16-bitserialcommunicationsfunctionswillhavetorelearnmanypartsofthesystemtoprogramserialcommunicationsproperly.Thisarticlewillhelptoaccomplishthis.Thoseunfamiliarwithserialcommunicationswillfindthisarticleahelpfulfoundationfordevelopmentefforts.
ThisarticleassumesthereaderisfamiliarwiththefundamentalsofmultiplethreadingandsynchronizationinWin32.Inaddition,abasicfamiliarityoftheWin32heapfunctionsisusefultofullycomprehendthememorymanagementmethodsusedbythesample,MTTTY,includedwiththisarticle.Formoreinformationregardingthesefunctions,consultthePlatformSDKdocumentation,theMicrosoftWin32SDKKnowledgeBase,ortheMicrosoftDeveloperNetworkLibrary.Applicationprogramminginterfaces(APIs)thatcontroluserinterfacefeaturesofwindowsanddialogboxes,thoughnotdiscussedhere,areusefultoknowinordertofullycomprehendthesampleprovidedwiththisarticle.ReadersunfamiliarwithgeneralWindowsprogrammingpracticesshouldlearnsomeofthefundamentalsofgeneralWindowsprogrammingbeforetakingonserialcommunications.Inotherwords,getyourfeetwetbeforedivinginheadfirst.
Introduction
Thefocusofthisarticleisonapplicationprogramminginterfaces(APIs)andmethodsthatarecompatiblewithMicrosoft®WindowsNT®andWindows95;therefore,APIssupportedonbothplatformsaretheonlyonesdiscussed.Windows95supportstheWin32®TelephonyAPI(TAPI)andWindowsNT3.xdoesnot;therefore,thisdiscussionwillnotincludeTAPI.TAPIdoesdeservemention,however,inthatitverynicelyimplementsmodeminterfacingandcallcontrolling.AproductionapplicationthatworkswithmodemsandmakestelephonecallsshouldimplementthesefeaturesusingtheTAPIinterface.ThiswillallowseamlessintegrationwiththeotherTAPI-enabledapplicationsthatausermayhave.Furthermore,thisarticledoesnotdiscusssomeoftheconfigurationfunctionsinWin32,suchasGetCommProperties.
Thearticleisbrokenintothefollowingsections:
Openingaport,readingandwriting(nonoverlappedandoverlapped),serialstatus(eventsanderrors),andserialsettings(DCB,flowcontrol,andcommunicationstime-outs).
Thesampleincludedwiththisarticle,MTTTY:
MultithreadedTTY,implementsmanyofthefeaturesdiscussedhere.Itusesthreethreadsinitsimplementation:
auserinterfacethreadthatdoesmemorymanagement,awriterthreadthatcontrolsallwriting,andareader/statusthreadthatreadsdataandhandlesstatuschangesontheport.Thesampleemploysafewdifferentdataheapsformemorymanagement.Italsomakesextensiveuseofsynchronizationmethodstofacilitatecommunicationbetweenthreads.
OpeningaPort
TheCreateFilefunctionopensacommunicationsport.TherearetwowaystocallCreateFiletoopenthecommunicationsport:
overlappedandnonoverlapped.Thefollowingistheproperwaytoopenacommunicationsresourceforoverlappedoperation:
HANDLEhComm;
hComm=CreateFile(gszPort,
GENERIC_READ|GENERIC_WRITE,
0,
0,
OPEN_EXISTING,
FILE_FLAG_OVERLAPPED,
0);
if(hComm==INVALID_HANDLE_VALUE)
//erroropeningport;abort
RemovaloftheFILE_FLAG_OVERLAPPEDflagfromthecalltoCreateFilespecifiesnonoverlappedoperation.Thenextsectiondiscussesoverlappedandnonoverlappedoperations.
ThePlatformSDKdocumentationstatesthatwhenopeningacommunicationsport,thecalltoCreateFilehasthefollowingrequirements:
∙fdwShareModemustbezero.Communicationsportscannotbesharedinthesamemannerthatfilesareshared.ApplicationsusingTAPIcanusetheTAPIfunctionstofacilitatesharingresourcesbetweenapplications.ForWin32applicationsnotusingTAPI,handleinheritanceorduplicationisnecessarytosharethecommunicationsport.Handleduplicationisbeyondthescopeofthisarticle;pleaserefertothePlatformSDKdocumentationformoreinformation.
∙fdwCreatemustspecifytheOPEN_EXISTINGflag.
∙hTemplateFileparametermustbeNULL.
OnethingtonoteaboutportnamesisthattraditionallytheyhavebeenCOM1,COM2,COM3,orCOM4.TheWin32APIdoesnotprovideanymechanismfordeterminingwhatportsexistonasystem.WindowsNTandWindows95keeptrackofinstalledportsdifferentlyfromoneanother,soanyonemethodwouldnotbeportableacrossallWin32platforms.Somesystemsevenhavemoreportsthanthetraditionalmaximumoffour.Hardwarevendorsandserial-device-driverwritersarefreetonametheportsanythingtheylike.Forthisreason,itisbestthatusershavetheabilitytospecifytheportnametheywanttouse.Ifaportdoesnotexist,anerrorwilloccur(ERROR_FILE_NOT_FOUND)afterattemptingtoopentheport,andtheusershouldbenotifiedthattheportisn’tavailable.
ReadingandWriting
ReadingfromandwritingtocommunicationsportsinWin32isverysimilartofileinput/output(I/O)inWin32.Infact,thefunctionsthataccomplishfileI/OarethesamefunctionsusedforserialI/O.I/OinWin32canbedoneeitheroftwoways:
overlappedornonoverlapped.ThePlatformSDKdocumentationusesthetermsasynchronousandsynchronoustoconnotethesetypesofI/Ooperations.Thisarticle,however,usesthetermsoverlappedandnonoverlapped.
NonoverlappedI/OisfamiliartomostdevelopersbecausethisisthetraditionalformofI/O,whereanoperationisrequestedandisassumedtobecompletewhenthefunctionreturns.InthecaseofoverlappedI/O,thesystemmayreturntothecallerimmediatelyevenwhenanoperationisnotfinishedandwillsignalthecallerwhentheoperationcompletes.TheprogrammayusethetimebetweentheI/Orequestanditscompletiontoperformsome“background”work.
ReadingandwritinginWin32issignificantlydifferentfromreadingandwritingserialcommunicationsportsin16-bitWindows.16-bitWindowsonlyhastheReadCommandWriteCommfunctions.Win32readingandwritingcaninvolvemanymorefunctionsandchoices.Theseissuesarediscussedbelow.
NonoverlappedI/O
NonoverlappedI/Oisverystraightforward,thoughithaslimitations.Anoperationtakesplacewhilethecallingthreadisblocked.Oncetheoperationiscomplete,thefunctionreturnsandthethreadcancontinueitswork.ThistypeofI/OisusefulformultithreadedapplicationsbecausewhileonethreadisblockedonanI/Ooperation,otherthreadscanstillperformwork.Itistheresponsibilityoftheapplicationtoserializeaccesstotheportcorrectly.IfonethreadisblockedwaitingforitsI/Ooperationtocomplete,allotherthreadsthatsubsequentlycallacommunicationsAPIwillbeblockeduntiltheoriginaloperationcompletes.Forinstance,ifonethreadwerewaitingforaReadFilefunctiontoreturn,anyotherthreadthatissuedaWriteFilefunctionwouldbeblocked.
Oneofthemanyfactorstoconsiderwhenchoosingbetweennonoverlappedandoverlappedoperationsisportability.Overlappedoperationisnotagoodchoicebecausemostoperatingsystemsdonotsupportit.Mostoperatingsystemssupportsomeformofmultithreading,however,somultithreadednonoverlappedI/Omaybethebestchoiceforportabilityreasons.
OverlappedI/O
OverlappedI/OisnotasstraightforwardasnonoverlappedI/O,butallowsmoreflexibilityandefficiency.AportopenforoverlappedoperationsallowsmultiplethreadstodoI/Ooperationsatthesametimeandperformotherworkwhiletheoperationsarepending.Furthermore,thebehaviorofoverlappedoperationsallowsasinglethreadtoissuemanydifferentrequestsanddoworkinthebackgroundwhiletheoperationsarepending.
Inbothsingle-threadedandmultithreadedapplications,somesynchronizationmusttakeplacebetweenissuingrequestsandprocessingtheresults.Onethreadwillhavetobeblockeduntiltheresultofanoperationisavailable.TheadvantageisthatoverlappedI/Oallowsathreadtodosomeworkbetweenthetimeoftherequestanditscompletion.Ifnoworkcanbedone,thentheonlycaseforoverlappedI/Oisthatitallowsforbetteruserresponsiveness.
OverlappedI/OisthetypeofoperationthattheMTTTYsampleuses.Itcreatesathreadthatisresponsibleforreadingtheport’sdataandreadingtheport’sstatus.Italsoperformsperiodicbackgroundwork.Theprogramcreatesanotherthreadexclusivelyforwritingdataouttheport.
Note Applicationssometimesabusemultithreadingsystemsbycreatingtoomanythreads.Althoughusingmultiplethreadscanresolvemanydifficultproblems,creatingexcessivethreadsisnotthemostefficientuseoftheminanapplication.ThreadsarelessastrainonthesystemthanprocessesbutstillrequiresystemresourcessuchasCPUtimeandmemory.Anapplicationthatcreatesexcessivethreadsmayadverselyaffecttheperformanceoftheentiresystem.AbetteruseofthreadsistocreateadifferentrequestqueueforeachtypeofjobandtohaveaworkerthreadissueanI/Orequestforeachentryintherequestqueue.ThismethodisusedbytheMTTTYsampleprovidedwiththisarticle.
AnoverlappedI/Ooperationhastwoparts:
thecreationoftheoperationandthedetectionofitscompletion.CreatingtheoperationentailssettingupanOVERLAPPEDstructure,creatingamanual-reseteventforsynchronization,andcallingtheappropriatefunction(ReadFileorWriteFile).TheI/Ooperationmayormaynotbecompletedimmediately.Itisanerrorforanapplicationtoa
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Serial Communications in Win32