Tải bản đầy đủ - 0 (trang)
Chapter 7. Console Programming and the Shell

Chapter 7. Console Programming and the Shell

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

WhereasonWindowstheshellistheshell,onUNIX-like

systems,thereareseveralkindsofshellsthatyoucanuse.

BothMacintoshandLinuxhaveterminalapplicationsthatyou

canusetoaccesstheshell,buttheactualshellbeingaccessed

canvarysh,bash,andtcsharealldifferentshellsthatcanbe

used.Intheseexamples,I'musingsh,althoughtheothertwo

areverycommon.ThegoodnewsisthatwhenusingtheShell

class,youcanspecifywhichshelltouse,sothatgivesyou

somecontrol.Otherwise,thesystemsthemselvesdecidewhat

thedefaultshellis,andthismightcauseunintended

consequencesifyouassumedoneshellandgotadifferentone.

Aconsoleapplicationisonethatcanbeexecutedfromthe

shell.Aconsoleapplicationislaunchedbytypingthenameof

theapplicationintotheshellandpressingtheEnterkey.All

shellshaveacoregroupofcommands,whicharereallyjust

smallapplicationsthatperformsomeverybasictaskssuchas

changingdirectoriesandmovingandcopyingfiles.Arguments

canalsobepassedtotheapplicationfromthecommandline.

Here'sanexamplethatissimilaronbothWindowsandUNIX-



likeoperatingsystems.First,takealookattheWindows

version:

cd"C:\ProgramFiles"



Figure7.1showshowthecommandlookswhenenteredintoa

WindowsCommandPromptapplication:

Next,theMacintoshandLinuxversions:

cd/usr/local/bin



Figure7.2showsthesamecommandenteredintothe

Macintoshterminalapplication,usingthebashshell,whichis

identifiedinthewindowtitle:



Figure7.2.MacintoshTerminal,BashShell.



Inbothcases,youarechangingintoapproximatelyequivalent

directories.The"cd"standsfor"changedirectory,"andthatis

alsothenameofthecommand(orapplication)beingexecuted.

Whatfollowsistheargument,whichispassedtotheprogram

whenitisexecuted,muchinthesamewaythatargumentsare

passedtosubroutinesandfunctions.

Inbothexamples,Ijusttypedincdandtheprogramexecuted,

butwithmostapplicationsyounormallywouldneedtotypein

theactualpathtotheapplication,likethisLinuxexample

shows:

/usr/bin/cd/usr/local/bin



Thereasonyoudonothavetoentertheentirepathisbecause

allsystemshaveaPATHenvironmentvariablethatliststhe

pathsthatshouldbecheckedwheneveracommandisentered

onthecommandlinethatdoesn'tuseanabsolutepath.By

default,WindowsandtheUNIX-likesystemsareconfiguredto

beabletoexecutethecdcommandwithoutthepath.The

environmentvariablesusedareusuallyuserspecificandcanbe

customized.However,whenusingtheShellclass,youcannot

assumethatthePATHhasbeensetforanything.

Whenyoucreateadesktopapplication,youdesignagraphical

userinterface,andthisinterfacerespondstouseractionsto

determinewhattodonext.Theuserinputcomesintheformof

mouseclicksordragsandthelike,andbyandlarge,the

responsetouserinputisdisplayedintheinterfaceitselfin

particular,windowsandcontrols.Becauseaconsoleapplication

isnotgraphical,itneedsanotherwaytogetuserinput,and

anotherwaytodisplayorviewtheresponsetothat

inputsomethingthatiscalledoutputinconsoleapplications.

Whenyoustartaconsoleapplicationandincludeanargument

inthecommand,youareusingaspecialkindofinputcalled



standardinput.Themostcommonwaytoprovideinputtoa

consoleapplicationisonthecommandlineitself.Afterthe

applicationrunsandcomputeswhateverneedstobecomputed,

itusuallysendsoutputtotheconsoleintheformoftext.

Sometimestheoutputisastatusmessage,andothertimesthe

outputisactuallywhattheprogramdoes.

I'llshowyouanexamplelaterwhereyoupasstwoarguments

toaconsoleapplication.Theargumentsarepathstoparticular

files.ThefirstargumentpointstoanXMLdocumentandthe

secondargumentpointstoanXSLTstylesheet.Theapplication

takesthatinput,findsthefiles,performsthetransformation,

andsendstheoutputtotheconsole.Thisiscalledstandard

output.That'ssimpleenough;thedatathatgoesiniscalled

standardinputandthedatathatgoesoutiscalledstandard

output.There'salsosomethingcalledstandarderror,whichis

whereerrormessagesgo(itsohappensthatitusuallygets

displayedinthesamewayasthestandardoutput,butyoucan

alsodesignateafileforstandarderrordatatobesent).

Therearealsosomeveryinterestingthingsthatcanbedone

withstandardinputandstandardoutput.Forexample,the

standardinputintooneprogramcouldbethestandardoutput

fromanother.Thisiscalledpiping,andit'satechniqueyoucan

usetosenddatathroughaseriesoftransformationsperformed

byacollectionofapplications.



SampleApplications

TheShellclassprovidesawayforREALbasictointeractwith

thecommandlinethroughanobject-orientedinterface.This

meansthatyouusetheShelltoexecuteapplicationsandto

passargumentstotheapplication,justlikeyouweretypingthe

informationyourselfintotheterminal.TheShellclasswillbe

coveredfirst.ThediscussionincludesanapplicationcalledAnt

ShellthatprovidesagraphicalinterfacetoAnt,whichisan

open-sourceJavaapplicationdevelopedbytheApache

Foundation.ItwasdevelopedtobuildJavaapplications,similar

tothewaythatMakeisusedtobuildC++applications,butitis

anextremelypowerful,easy-to-usetool,anditisnormallyrun

fromthecommandline.ThereasonIhavechosentosharean

AntapplicationwithyouisthatAntbuildfilesareXML

documents,soinadditiontointroducingtheShell,italso

providesalittlemoreinsightintohowyoucanuseXML

technology.

AftertheShell,Iwillturntodevelopinganactualconsole

applicationinREALbasic(youcouldactuallyexecutea

REALbasicconsoleapplicationusingtheShellclass,ifyou

wantedto,butinmostcases,Idon'tthinkthat'sasmartway

tobedoingthings).Thefirstconsoleapplicationiscalled

Transformer,anditprovidesacommand-lineinterfacetothe

XMLDocumentandXSLStyleSheetclassesinREALbasic.The

classusedtodothetransformingwillbewrittensothatitcan

beusedinaconsoleapplicationaswellasinadesktop

application.ThismeansthatIwillbeabletousethesameclass

intheRSSReaderapplicationthatIuseintheTransformer

application.

I'llalsobeabletousethesameclassinanotherconsole

application,calledrbCGI,whichwillserveasthefinalexample.

ThisconsoleapplicationisasimpleframeworkforwritingCGI

programs.CGIreferstotheCommonGatewayInterface,which



isonemethodthatisusedtoexecutescriptsandprogramsto

dynamicallygeneratewebsites.It'sreallyasimpleframework

withalotoflimitationsdefinitelynotsomethingyouwoulduseif

youhadaveryhigh-trafficsite.However,ifyouhaverelatively

simpleneeds,itcanworkquitewell.TheCGIframeworkcould

beusedasawaytodistributedynamicallyproducedRSSXML

documents,oritcouldbeanalternativewaytoviewRSSfiles

asHTML.

ThereareafewinterestingpointsabouttheCGIapplication

worthmentioninghere.First,itshowshowstandardinputand

standardoutputcanbeusedindifferentcontexts.Inthecase

oftheCGIapplication,standardoutputissentbacktotheweb

browseroftheindividualwhomadetheoriginalHTTPrequest,

ratherthanbeingsenttotheterminal.Also,someofthedata

usedbytheCGIapplicationispassedinenvironmentvariables.

CGIapplicationscanuseeitherstandardinputorthecontentof

environmentvariablesasthesourceofdatausedtoexecutethe

application.

Intheongoingefforttodemonstratethejoysofcodereuse,the

CGIapplicationwillalsousethesameclassthat'susedto

transformXMLdocumentsintheRSSReaderapplicationandthe

Transformerapplication.ThiswillallowtheCGIapplicationto

getarequest,findanRSSfile,transformittoHTML,and

presentittotheuser.YoucanthinkofitasastarttoawebenabledversionoftheRSSReaderapplicationIhavebeen

reviewingthroughoutthebook.Infact,afteryou'veread

throughtheexamples,youwillbegintothinkofalotofways

thatthesedifferentexamplescaninteractwitheachother.



TheShellClass

TheShellclasscanberuninthreemodes:synchronous,

asynchronous,andinteractive.Themodeissetusingthe

Shell.Modeproperty,whichisdescribednext.Whenusing

synchronousmode,youusetheShellclasstoexecutea

commandandthengettheresultsbackimmediately.Thisisa

blockingmethod,whichmeansthatnothingelsehappensinthe

sequenceofcodeuntiltheresultsarereturned.Using

asynchronousmode,youcanexecuteacommand,butyoudo

notneedtowaitfortheresults.Instead,youwaitforthe

DataAvailableeventtobetriggered.Interactivemodeissimilarto

asynchronousmodeexceptthatinsteadofexecutingonlyone

command,youcanexecuteseveralcommandsinsequence,

basedontheresultsfromthepreviouscommand.

AlthoughsynchronousmodeisasimplewaytoruntheShell,I

thinkrunningitasynchronouslyorinteractivelyprovidesalot

moreflexibility.Becausethetwononsynchronousmodesrelyon

events,theShellisoftenusedlikeacontrolandcanbe

draggedtoaWindowandprogrammedthere.Thesample

applicationtreatstheShelllikeacontrol.



ShellProperties

WhethertheShellissynchronous,asynchronous,orinteractive

isdeterminedbytheModeproperty:

Shell.ModeasInteger



Thevaluesyoucanuseare



Synchronous 0



Asynchronous 1

Interactive



2



Thesevaluescanbesetatruntime.



SynchronousExecution

ThefollowingpropertiesareusedwhenrunningtheShellin

synchronousmode.PriortoREALbasic2005,Windowshadto

usesynchronousmode,butitdoesn'tanylonger,soyouwill

probablynotneedtousethese:

Shell.TimeOutasInteger



TimeOutismeasuredinmillisecondsandisusedonlywhen



runningsynchronouslyonWindows.Use-1towaitindefinitely

fortheresults.

Shell.ErrorCodeasInteger



TheErrorCodeissuppliedbythesystem.It'sazeroifalliswell,

andanothernumberifthereisaproblem.Whenyouexecutea

commandinsynchronousmode,youshouldchecktheresult

andifitiszero,youcanretrievethestandardoutputofthe

commandusingthefollowingproperty:



Shell.ResultasString



Thisisusedonlyinsynchronousmode,anditcontainsthe

entireoutput.Intheothermodes,youwillusetheReadAll

methodtoaccessthelatestdata.



AsynchronousandInteractiveExecution

Thefollowingtwopropertiesareusedwhenusingmodesother

thansynchronous.ThefirstcheckstoseewhethertheShellis

stillrunning,andthesecondistheprocessIDnumberofan

interactiveShellprocess:

Shell.IsRunningasBoolean

Shell.PIDasInteger



ShellEvents

Thefollowingeventsaretriggeredonlywhenusing

asynchronousorinteractivemodes.Thefollowingeventis

triggeredwhennewdataisavailableinthebuffer:

Shell.DataAvailableHandlesEvent



WhentheDataAvailableeventistriggered,youcanretrievethe

mostrecentdatafromthebufferbycallingtheReadAllmethod.

Thefollowingeventletsyouknowthatallthedatahasbeen

sentandtheprocessthatyouinitiatedwiththeexecutionofthe



commandhasterminated:

Shell.CompletedHandlesEvent



ShellMethods

YouexecuteanapplicationbycallingtheShell.Executemethod:

Shell.Execute(CommandasString,[ParametersasString])



Therearetwowaystopassargumentstothemethod.The

Commandparameterrepresentsthepathtotheactualapplication

orprogramthatistobeexecuted(unlesstheappropriatePATH

environmentvariablehasbeenset,andthenyoucanjustuse

thenameoftheapplication).TheoptionalParametersparameter

canbeusedwithadditionalargumentsthatgetpassedtothe

program.YoucanincludetheargumentsintheCommand

parameter,buttheREALbasicdocumentationsuggeststhatyou

usetheParametersparameteriftherearespacesinthepathto

theapplicationbeingexecuted.

Forexample,ifthereisaShellinstance,Shell1,youcan

executethe"cd"commandusedearlier,likethis:

Shell1.Execute("cd/usr/local/bin")



Oryoucanuseitlikethis:

Shell1.Execute("cd","/usr/local/bin")



Whenusingasynchronousorinteractivemode,youcancallthe

pollmethod,whichmaytriggeraDataAvailableevent.Generally

speaking,Idon'tthinkit'snecessarytouse.Novalueis

returned;theonlyresponseisthepossibletriggeringofthe

DataAvailableevent.

Shell.Poll



Thefollowingmethodaccessesthedatabuffer.Whencalled,it

returnsallthedatainthebufferandthenclearsthebuffer.This

isusedinasynchronousandinteractivemodesonly.

Shell.ReadAllasString



Therearetwomethodsusedtosendadditionaltexttothe

commandline.Itisusedwhenyouareininteractivemodeand

yourclassneedstosendadditionaldatatothecommand-line

applicationbasedonarequestfromtheapplication.The

WriteLinemethodappendsalinefeedtothestring,whichisthe

equivalentofpressingtheEnterkeyaftertypingyourcommand

intotheshell.

Shell.Write(TextasString)

Shell.WriteLine(TextasString)



Thefollowingmethodclosestheshell:

Shell.Close



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

Chapter 7. Console Programming and the Shell

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

×