Transcription of Chapter 1 Introduction to System Programming
1 UNIXL ectureNotesChapter1 IntroductiontoSystemProgrammingStewartWe issChapter1 Intro ductiontoSystemProgramming UNIX isbasicallyasimpleop eratingsystem,butyouhavetob eageniustounderstandthesimplicity. -DennisRitchie, ,Systemcal lsandlibraries,Processes,loginsandshel ls,Environments,manpages,Users,theroot,a ndgroups,Authentication,Filesystem, lehierarchy,Filesanddirectories,Devicesp ecial les,UNIX standards,POSIX,Systemprogramming,Termin alsandANSI escapesequences,HistoryofUNIX,syscal l,getpid, ductionAmo dernsoftwareapplicationtypicallyneedstom anageb , les,screendisplays, ewrittenasacollectionofco op eratingthreadsorsub-pro cessesthatco ordinatetheiractionswithresp dernop eratingsystemspreventapplicationsoftware frommanagingsystemresourcesdirectly.
2 Whenrunningonmo dernop eratingsystems,applicationscannotdrawtot hescreendirectlyorreadorwrite erformscreenop erationsor leI/Otheymustusetheinterfacethattheop eratingsystemde ()orfprintf()access lesdirectly,theydonot;theymakecallstosys temroutinesthatdotheworkontheirb eratingsystemforapplicationstousewhenacc essingsystemre-sourcesiscalledtheop eratingsystem'sapplicationprogrammingint erface(API).AnAPItypicallyconsistsofacol lectionoffunction,typ e,andconstantde nitions,andsometimesvariablede eratingsystemine ectde nesthemeansbywhichanapplicationcanutiliz etheservicesprovidedbythatop ' ,asidefromdesigningtheapplicationitself, themostimp ortanttaskfortheapplicationdevelop eristomasterthesystemlevelservicesde nedintheop eratingsystem' ,andthetyp eratingsystemandmayevenaccessthesystem1 Weusethetermplatformtomeanasp eci cop eratingsystemrunningonasp eci.
3 SimpleI/Omo delusedbyb ewrittentoextendthefunctionalityoftheop eci callyconcernsystemprogrammingusingtheAPI oftheUNIXop eriencewithUNIX asauser,butthismaterialcanb eskipp edbytheexp ,adistinctionwillb emadeb etweentheuser'sviewofUNIX andtheprogrammer' 'sviewofUNIX islimitedtoasubsetofcommandsthatcanb eenteredatthecommand-lineandpartsofthe lesarenotavailabletoallusers,aswillb 'sviewincludestheprogramminglanguagefeat uresofthekernelAPI,thefunctions,typ es,andconstantsinallofthelibraries,theva riousheader les,andthevarious eginningprogrammertypicallywritesprogram sthatfollowthesimpleI/Omo.
4 Theprogramgetsitsinputfromthekeyb oardoradisk le,andwritesitsoutputtothedisplayscreeno rtoa ecausethekeyb ,oneusingtheCStandardI/OLibrary,andtheot her,theC++ oardandsendoutputtothedisplaydevice, ,everypro cessiscreatedandloadedintomemory,UNIX automaticallycreatesthestandardinputands tandardoutputdevicesforit,op ensthem,andmakesthemreadyforreadingandwr itingresp (andC++),stdinandstdoutarevariablesde nedinthe< >2 Infact,everyPOSIX-compliantop eratingsystemmustprovideb le,thatrefertothestandardinputandstandar doutputdevice4resp ,thekeyb oardanddisplayoftheasso ciatedterminalarethestandardinputandoutp utdevicesresp :CprogramusingsimpleI/Omo del.
5 # i n c l u d e< s t d i o. h>/*c o p yf r o ms t d i nt os t d o u t*/i n tm a i n( ){i n tc;w h i l e((c=g e t c h a r( ))! =EOF)p u t c h a r(c) ;r e t u r n0 ;} :SimpleC++programusingsimpleI/Omo del.# i n c l u d e< i o s t r e a m >u s i n gn a m e s p a c es t d;/*c o p yf r o ms t d i nt os t d o u tu s i n gC++*/i n tm a i n( ){c h a rc;w h i l e((c=c i e t( ))&&!)}
6 C i o f( ))c o u u t (c) ;r e t u r n0 ;}Theseprogramsgiveustheillusionthatthey aredirectlyconnectedtothekeyb oardandthedisplaydeviceviaClibraryfuncti onsgetchar()andputchar()andtheC++iostrea mmemb erfunctionsget()andput().Eitherofthemcan b erunonasingle-userdesktopcomputeroronamu lti-user,time-sharedworkstationinatermin alwindow,andtheresultswillb ,theywillhavethesameb ersonalcomputerrunninginsingle-usermo de,thisillusionisnotfarfromrealityinthes ensethatthekeyb oardisindirectlyconnectedtotheinputstrea moftheprogram, eratingsystem,severalusersmayb eloggedinsimultaneously,andprogramsb elongingtodi erentusersmightb erunningatthesametime,eachreceivinginput fromadi erentkeyb oardandsendingoutputtoadi ,onaUNIX computeronanetworkintowhichyoucanlogin.
7 Manyp eoplemayb econnectedtoasinglecomputerviaanetworkpr ogramsuchasSSH,andseveralofthemwillb eabletoruntheab oveprogramonthesamecomputeratthesametime ,sendingtheiroutputtodi erentterminalwindowsonphysicallydi erentcomputers, ,UNIX ensures,inaremarkablyelegantmanner,thate achuser'sprocesseshavealogicalconnection totheirkeyb oardandtheirdisplay.(Thepro cessconceptwillb eexplained4 InCandC++,stderristhevariableasso )Programsthatusethemo delofI/Odescrib edab ovedonothavetob econcernedwiththecomplexitiesofconnectin gtomonitorsandkeyb oards,b ecausetheop eratingsystemhidesthatcomplexity,present ingasimpli eratingsystemachievesthis,onemust rstunderstandseveralcornerstoneconceptso ftheUNIXop eratingsystem: les,pro cesses,usersandgroups,privilegesandprote ctions, eginning,UNIX wasdesignedaroundasmallsetofcleverideas, asRitchieandThompson[2]putit.
8 ThesuccessofUNIX liesnotsomuchinnewinventionsbutratherint hefullexploita-tionofacarefullyselecteds etoffertileideas,andesp eciallyinshowingthattheycanb ekeystotheimplementationofasmallyetp owerfulop eratingsystem. Those fertileideas includedthedesignofits lesystem,itspro cessconcept,theconceptofprivilegedandunp rivilegedprograms,theconceptsofuserandgr oups,aprogrammableshell,environments,and deviceindep eeachofthesebrie eoplewhohaveusedcomputersknowwhata leis,butasanexercise,tryexplainingwhata ,butknowinghowtode ,thetraditionalde nitionofa lewasthat itisthesmal lestunitofexternalstorage.
9 "Externalstorage"hasalwaysmeantnon-volat ilestorage,notinprimarymemory,butonmedia suchasmagnetic,optical,andelectronicdisk s,tap esandsoon.(Internalstorageisonmemorychip s.)Thecontemp oraryde nitionofa leinUNIX isthatitisanob jectthatcanb ewrittento,orreadfrom,orb nitionofa lesintoatree-likehierarchythatmostp eopleerroneouslycallthe lehierarchy,b ecausea lesystemissomethingslightlydi ecialtyp esof lesthat,fromtheuserp ersp ective,app eartocontainother les,althoughtheydonotcontain lesanymorethanatableofcontentsinab o okcontainsthechaptersoftheb o eprecise,adirectoryisa jectthatasso ciatesa lenametoa otoftheUNIX lesystemisadirectoryknownintheUNIX worldastherootdirectory,howeveritisnotna med"root"inthe lesystem.
10 Itisnamed"/".Whenyouneedtorefertothisdir ectory,youcallit"ro ot",not"slash".Morewillb esaidab out les, lenames,andthe cessesAprogramisanexecutable le, ,itisgivenvariousresourcessuchasaprimary memoryspace,b othphysicalandlogical,secondarystoragesp ace,mappingsofvariouskinds6,andprivilege s,suchastherighttoreadorwritecertain ,atanyinstantoftime,asso ciatedtoapro cessisthecollectionofallresourcesallo catedtotherunningprogram,aswellasanyothe rprop ertiesandsettingsthatcharacterizethatpro cess,suchasthevaluesofthepro cessor' ,althoughtheideaofapro cesssoundslikeanabstractidea,itis,infact , cessauniquenumb ,atagiveninstantoftime.