4.2BSDSystemManual RevisedJuly,1983 WilliamJoy,EricCooper,RobertFabry, SamuelLeffler,KirkMcKusickandDavidMosher ComputerSystemsResearchGroup ComputerScienceDivision DepartmentofElectricalEngineeringandComputerScience UniversityofCalifornia,Berkeley Berkeley,CA94720 (415)642-7780 ABSTRACT Thisdocumentsummarizesthefacilitiesprovidedbythe4.2BSDversionof theUNIXoperatingsystem.Itdoesnotattempttoactasatutorialforuseof thesystemnordoesitattempttoexplainorjustifythedesignofthesystemfacilities.Itgivesneithermotivationnorimplementationdetails,infavorofbrevity. ThefirstsectiondescribesthebasickernelfunctionsprovidedtoaUNIX process:processnamingandprotection,memorymanagement,softwareinterrupts,objectreferences(descriptors),timeandstatisticsfunctions,andresource controls.Thesefacilities,aswellasfacilitiesforbootstrap,shutdownandprocess accounting,areprovidedsolelybythekernel. Thesecondsectiondescribesthestandardsystemabstractionsforfilesand filesystems,communication,terminalhandling,andprocesscontrolanddebugging.Thesefacilitiesareimplementedbytheoperatingsystemorbynetwork serverprocesses. *UNIXisatrademarkofBellLaboratories.

4.2BSDSystemManual -i- Contents TABLEOFCONTENTS Introduction. 0.Notationandtypes 1.Kernelprimitives 1.1.Processesandprotection .1.Hostandprocessidentifiers .2.Processcreationandtermination .3.Userandgroupids .4.Processgroups 1.2.Memorymanagement .1.Text,dataandstack .2.Mappingpages .3.Pageprotectioncontrol .4.Givingandgettingadvice 1.3.Signals .1.Overview .2.Signaltypes .3.Signalhandlers .4.Sendingsignals .5.Protectingcriticalsections .6.Signalstacks 1.4.Timingandstatistics .1.Realtime .2.Intervaltime 1.5.Descriptors .1.Thereferencetable .2.Descriptorproperties .3.Managingdescriptorreferences .4.Multiplexingrequests .5.Descriptorwrapping 1.6.Resourcecontrols .1.Processpriorities .2.Resourceutilization .3.Resourcelimits 1.7.Systemoperationsupport .1.Bootstrapoperations .2.Shutdownoperations .3.Accounting CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual -ii- Contents 2.Systemfacilities 2.1.Genericoperations .1.Readandwrite .2.Input/outputcontrol .3.Non-blockingandasynchronousoperations 2.2.Filesystem .1Overview .2.Naming .3.Creationandremoval .3.1.Directorycreationandremoval .3.2.Filecreation .3.3.Creatingreferencestodevices .3.4.Portalcreation .3.6.File,device,andportalremoval .4.Readingandmodifyingfileattributes .5.Linksandrenaming .6.Extensionandtruncation .7.Checkingaccessibility .8.Locking .9.Discquotas 2.3.Inteprocesscommunication .1.Interprocesscommunicationprimitives .1.1.Communicationdomains .1.2.Sockettypesandprotocols .1.3.Socketcreation,namingandserviceestablishment .1.4.Acceptingconnections .1.5.Makingconnections .1.6.Sendingandreceivingdata .1.7.Scatter/gatherandexchangingaccessrights .1.8.Usingreadandwritewithsockets .1.9.Shuttingdownhalvesoffull-duplexconnections .1.10.Socketandprotocoloptions .2.UNIXdomain .2.1.Typesofsockets .2.2.Naming .2.3.Accessrightstransmission .3.INTERNETdomain .3.1.Sockettypesandprotocols .3.2.Socketnaming .3.3.Accessrightstransmission .3.4.Rawaccess 2.4.Terminalsanddevices .1.Terminals .1.1.Terminalinput .1.1.1Inputmodes .1.1.2Interruptcharacters .1.1.3Lineediting .1.2.Terminaloutput .1.3.Terminalcontroloperations .1.4.Terminalhardwaresupport .2.Structureddevices CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-iii- Contents .3.Unstructureddevices 2.5.Processcontrolanddebugging I.Summaryoffacilities CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual -1- Contents 1.Notation ThenotationusedtodescribesystemcallsisavariantofaClanguagecall,consistingofa prototypecallfollowedbydeclarationofparametersandresults.Anadditionalkeywordresult, notpartofthenormalClanguage,isusedtoindicatewhichofthedeclaredentitiesreceive results.Asanexample,considerthereadcall,asdescribedinsection2.1: cc=read(fd,buf,nbytes); resultintcc;intfd;resultchar*buf;intnbytes; Thefirstlineshowshowthereadroutineiscalled,withthreeparameters.Asshownonthesecondlineccisanintegerandreadalsoreturnsinformationintheparameterbuf. Descriptionofallerrorconditionsarisingfromeachsystemcallisnotprovidedhere;they appearintheprogrammer’smanual.Inparticular,whenaccessedfromtheClanguage,many callsreturnacharacteristic−1valuewhenanerroroccurs,returningtheerrorcodeintheglobal variableerrno.Otherlanguagesmaypresenterrorsindifferentways. Anumberofsystemstandardtypesaredefinedintheincludefile<sys/types.h>andused inthespecificationshereandinmanyCprograms.Theseincludecaddrtgivingamemory address(typicallyasacharacterpointer),offtgivingafileoffset(typicallyasalonginteger), andasetofunsignedtypesuchar,ushort,uintandulong,shorthandnamesforunsigned char,unsignedshort,etc. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual -2- Kernelprimitives 2.Kernelprimitives ThefacilitiesavailabletoaUNIXuserprocessarelogicallydividedintotwoparts:kernel facilitiesdirectlyimplementedbyUNIXcoderunningintheoperatingsystem,andsystemfacilitiesimplementedeitherbythesystem,orincooperationwithaserverprocess.Thesekernelfacilitiesaredescribedinthissection1. ThefacilitiesimplementedinthekernelarethosewhichdefinetheUNIXvirtualmachine whicheachprocessrunsin.Likemanyrealmachines,thisvirtualmachinehasmemorymanagementhardware,aninterruptfacility,timersandcounters.TheUNIXvirtualmachinealsoallows accesstofilesandotherobjectsthroughasetofdescriptors.Eachdescriptorresemblesadevice controller,andsupportsasetofoperations.Likedevicesonrealmachines,someofwhichare internaltothemachineandsomeofwhichareexternal,partsofthedescriptormachineryare built-intotheoperatingsystem,whileotherpartsareoftenimplementedinserverprocesseson othermachines.Thefacilitiesprovidedthroughthedescriptormachineryaredescribedinsection 2. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual -3-Processesandprotection 2.1.Processesandprotection 2.1.1.Hostandprocessidentifiers EachUNIXhosthasassociatedwithita32-bithostid,andahostnameofupto255char-acters.Theseareset(byaprivilegeduser)andreturnedbythecalls: sethostid(hostid) longhostid; hostid=gethostid(); resultlonghostid; sethostname(name,len) char*name;intlen; len=gethostname(buf,buflen) resultintlen;resultchar*buf;intbuflen; Oneachhostrunsasetofprocesses.Eachprocessislargelyindependentofotherprocesses,havingitsownprotectiondomain,addressspace,timers,andanindependentsetofreferencestosystemoruserimplementedobjects. Eachprocessinahostisnamedbyanintegercalledtheprocessid.Thisnumberisinthe range1-30000andisreturnedbythegetpidroutine: pid=getpid(); resultintpid; OneachUNIXhostthisidentifierisguaranteedtobeunique;inamulti-hostenvironment,the (hostid,processid)pairsareguaranteedunique. 2.1.2.Processcreationandtermination Anewprocessiscreatedbymakingalogicalduplicateofanexistingprocess: pid=fork(); resultintpid; Theforkcallreturnstwice,onceintheparentprocess,wherepidistheprocessidentifierofthe child,andonceinthechildprocesswherepidis0.Theparent-childrelationshipinducesahierar-chicalstructureonthesetofprocessesinthesystem. Aprocessmayterminatebyexecutinganexitcall: exit(status) intstatus; returning8bitsofexitstatustoitsparent. Whenachildprocessexitsorterminatesabnormally,theparentprocessreceivesinformation aboutanyeventwhichcausedterminationofthechildprocess.Asecondcallprovidesanonblockinginterfaceandmayalsobeusedtoretrieveinformationaboutresourcesconsumedbythe processduringitslifetime. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual -4-Processesandprotection #include<sys/wait.h> pid=wait(astatus); resultintpid;resultunionwait*astatus; pid=wait3(astatus,options,arusage); resultintpid;resultunionwaitstatus*astatus; intoptions;resultstructrusage*arusage; Aprocesscanoverlayitselfwiththememoryimageofanotherprocess,passingthenewly createdprocessasetofparameters,usingthecall: execve(name,argv,envp) char*name,**argv,**envp; Thespecifiednamemustbeafilewhichisinaformatrecognizedbythesystem,eitherabinary executablefileorafilewhichcausestheexecutionofaspecifiedinterpreterprogramtoprocessits contents. 2.1.3.Userandgroupids Eachprocessinthesystemhasassociatedwithittwouser-id’s:arealuseridandaeffective userid,bothnon-negative16bitintegers.Eachprocesshasanrealaccountinggroupidandan effectiveaccountinggroupidandasetofaccessgroupid’s.Thegroupid’sarenon-negative16bit integers.Eachprocessmaybeinseveraldifferentaccessgroups,withthemaximumconcurrent numberofaccessgroupsasystemcompilationparameter,theconstantNGROUPSinthefile <sys/param.h>,guaranteedtobeatleast8. Therealandeffectiveuseridsassociatedwithaprocessarereturnedby: ruid=getuid(); resultintruid; euid=geteuid(); resultinteuid; therealandeffectiveaccountinggroupidsby: rgid=getgid(); resultintrgid; egid=getegid(); resultintegid; andtheaccessgroupidsetisreturnedbyagetgroupscall: ngroups=getgroups(gidsetsize,gidset); resultintngroups;intgidsetsize;resultintgidset[gidsetsize]; Theuserandgroupid’sareassignedatlogintimeusingthesetreuid,setregid,andsetgroups calls: CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual -5-Processesandprotection setreuid(ruid,euid); intruid,euid; setregid(rgid,egid); intrgid,egid; setgroups(gidsetsize,gidset) intgidsetsize;intgidset[gidsetsize]; Thesetreuidcallsetsboththerealandeffectiveuser-id’s,whilethesetregidcallsetsboththereal andeffectiveaccountinggroupid’s.Unlessthecalleristhesuper-user,ruidmustbeequalto eitherthecurrentrealoreffectiveuser-id,andrgidequaltoeitherthecurrentrealoreffective accountinggroupid.Thesetgroupscallisrestrictedtothesuper-user. 2.1.4.Processgroups Eachprocessinthesystemisalsonormallyassociatedwithaprocessgroup.Thegroupof processesinaprocessgroupissometimesreferredtoasajobandmanipulatedbyhigh-levelsys-temsoftware(suchastheshell).Thecurrentprocessgroupofaprocessisreturnedbythegetp-grpcall: pgrp=getpgrp(pid); resultintpgrp;intpid; Whenaprocessisinaspecificprocessgroupitmayreceivesoftwareinterruptsaffectingthe group,causingthegrouptosuspendorresumeexecutionortobeinterruptedorterminated.In particular,asystemterminalhasaprocessgroupandonlyprocesseswhichareintheprocess groupoftheterminalmayreadfromtheterminal,allowingarbitrationofterminalsamongseveral differentjobs. Theprocessgroupassociatedwithaprocessmaybechangedbythesetpgrpcall: setpgrp(pid,pgrp); intpid,pgrp; Newlycreatedprocessesareassignedprocessid’sdistinctfromallprocessesandprocessgroups, andthesameprocessgroupastheirparent.Anormal(unprivileged)processmaysetitsprocess groupequaltoitsprocessid.Aprivilegedprocessmaysettheprocessgroupofanyprocessto anyvalue. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual -6- Memorymanagement† 2.2.Memorymanagement† 2.2.1.Text,dataandstack Eachprocessbeginsexecutionwiththreelogicalareasofmemorycalledtext,dataand stack.Thetextareaisread-onlyandshared,whilethedataandstackareasareprivatetothe process.Boththedataandstackareasmaybeextendedandcontractedonprogramrequest. Thecall addr=sbrk(incr); resultcaddrtaddr;intincr; changesthesizeofthedataareabyincrbytesandreturnsthenewendofthedataarea,while addr=sstk(incr); resultcaddrtaddr;intincr; changesthesizeofthestackarea.Thestackareaisalsoautomaticallyextendedasneeded.On theVAXthetextanddataareasareadjacentintheP0region,whilethestacksectionisinthe P1region,andgrowsdownward. 2.2.2.Mappingpages Thesystemsupportssharingofdatabetweenprocessesbyallowingpagestobemappedinto memory.Thesemappedpagesmaybesharedwithotherprocessesorprivatetotheprocess.Protectionandsharingoptionsaredefinedin<mman.h>as: /*protectionsarechosenfromthesebits,or-edtogether*/ #definePROTREAD0x4/*pagescanberead*/ #definePROTWRITE0x2/*pagescanbewritten*/ #definePROTEXEC0x1/*pagescanbeexecuted*/ /*sharingtypes;chooseeitherSHAREDorPRIVATE*/ #defineMAPSHARED1/*sharechanges*/ #defineMAPPRIVATE2/*changesareprivate*/ Thecpu-dependentsizeofapageisreturnedbythegetpagesizesystemcall: pagesize=getpagesize(); resultintpagesize; Thecall: mmap(addr,len,prot,share,fd,pos); caddrtaddr;intlen,prot,share,fd;offtpos; causesthepagesstartingataddrandcontinuingforlenbytestobemappedfromtheobjectrepresentedbydescriptorfd,atabsolutepositionpos.Theparametersharespecifieswhethermodificationsmadetothismappedcopyofthepage,aretobekeptprivate,oraretobesharedwith otherreferences.Theparameterprotspecifiestheaccessibilityofthemappedpages.Theaddr, len,andposparametersmustallbemultiplesofthepagesize. Aprocesscanmovepageswithinitsownmemorybyusingthemremapcall: mremap(addr,len,prot,share,fromaddr); caddrtaddr;intlen,prot,share;caddrtfromaddr; Thiscallmapsthepagesstartingatfromaddrtotheaddressspecifiedbyaddr. †Thissectionrepresentstheinterfaceplannedforlaterreleasesofthesystem.Ofthecallsdescribed inthissection,onlysbrkandgetpagesizeareincludedin4.2BSD. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual -7- Memorymanagement† Amappingcanberemovedbythecall munmap(addr,len); caddrtaddr;intlen; Thiscausesfurtherreferencestothesepagestorefertoprivatepagesinitializedtozero. 2.2.3.Pageprotectioncontrol Aprocesscancontroltheprotectionofpagesusingthecall mprotect(addr,len,prot); caddrtaddr;intlen,prot; Thiscallchangesthespecifiedpagestohaveprotectionprot. 2.2.4.Givingandgettingadvice Aprocessthathasknowledgeofitsmemorybehaviormayusethemadvisecall: madvise(addr,len,behav); caddrtaddr;intlen,behav; Behavdescribesexpectedbehavior,asgivenin<mman.h>: #defineMADVNORMAL0/*nofurtherspecialtreatment*/ #defineMADVRANDOM1/*expectrandompagereferences*/ #defineMADVSEQUENTIAL2/*expectsequentialreferences*/ #defineMADVWILLNEED3/*willneedthesepages*/ #defineMADVDONTNEED4/*don’tneedthesepages*/ Finally,aprocessmayobtaininformationaboutwhetherpagesarecoreresidentbyusingthecall mincore(addr,len,vec) caddrtaddr;intlen;resultchar*vec; Herethecurrentcoreresidencyofthepagesisreturnedinthecharacterarrayvec,withavalueof 1meaningthatthepageisin-core. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual -8- Signals 2.3.Signals 2.3.1.Overview Thesystemdefinesasetofsignalsthatmaybedeliveredtoaprocess.Signaldelivery resemblestheoccurrenceofahardwareinterrupt:thesignalisblockedfromfurtheroccurrence, thecurrentprocesscontextissaved,andanewoneisbuilt.Aprocessmayspecifythehandlerto whichasignalisdelivered,orspecifythatthesignalistobeblockedorignored.Aprocessmay alsospecifythatadefaultactionistobetakenwhensignalsoccur. Somesignalswillcauseaprocesstoexitwhentheyarenotcaught.Thismaybeaccompaniedbycreationofacoreimagefile,containingthecurrentmemoryimageoftheprocessforuse inpost-mortemdebugging.Aprocessmaychoosetohavesignalsdeliveredonaspecialstack,so thatsophisticatedsoftwarestackmanipulationsarepossible. Allsignalshavethesamepriority.Ifmultiplesignalsarependingsimultaneously,theorder inwhichtheyaredeliveredtoaprocessisimplementationspecific.Signalroutinesexecutewith thesignalthatcausedtheirinvocationblocked,butothersignalsmayyetoccur.Mechanismsare providedwherebycriticalsectionsofcodemayprotectthemselvesagainsttheoccurrenceofspecifiedsignals. 2.3.2.Signaltypes Thesignalsdefinedbythesystemfallintooneoffiveclasses:hardwareconditions,software conditions,input/outputnotification,processcontrol,orresourcecontrol.Thesetofsignalsis definedinthefile<signal.h>. Hardwaresignalsarederivedfromexceptionalconditionswhichmayoccurduringexecution. SuchsignalsincludeSIGFPErepresentingfloatingpointandotherarithmeticexceptions,SIGILL forillegalinstructionexecution,SIGSEGVforaddressesoutsidethecurrentlyassignedareaof memory,andSIGBUSforaccessesthatviolatememoryprotectionconstraints.Other,morecpuspecifichardwaresignalsexist,suchasthoseforthevariouscustomer-reservedinstructionsonthe VAX(SIGIOT,SIGEMT,andSIGTRAP). Softwaresignalsreflectinterruptsgeneratedbyuserrequest:SIGINTforthenormalinterruptsignal;SIGQUITforthemorepowerfulquitsignal,thatnormallycausesacoreimagetobe generated;SIGHUPandSIGTERMthatcausegracefulprocesstermination,eitherbecauseauser has‘‘hungup’’,orbyuserorprogramrequest;andSIGKILL,amorepowerfulterminationsignal whichaprocesscannotcatchorignore.Othersoftwaresignals(SIGALRM,SIGVTALRM,SIG-PROF)indicatetheexpirationofintervaltimers. AprocesscanrequestnotificationviaaSIGIOsignalwheninputoroutputispossibleona descriptor,orwhenanon-blockingoperationcompletes.AprocessmayrequesttoreceiveaSIG-URGsignalwhenanurgentconditionarises. Aprocessmaybestoppedbyasignalsenttoitorthemembersofitsprocessgroup.The SIGSTOPsignalisapowerfulstopsignal,becauseitcannotbecaught.OtherstopsignalsSIGT-STP,SIGTTIN,andSIGTTOUareusedwhenauserrequest,inputrequest,oroutputrequest respectivelyisthereasontheprocessisbeingstopped.ASIGCONTsignalissenttoaprocess whenitiscontinuedfromastoppedstate.ProcessesmayreceivenotificationwithaSIGCHLD signalwhenachildprocesschangesstate,eitherbystoppingorbyterminating. Exceedingresourcelimitsmaycausesignalstobegenerated.SIGXCPUoccurswhenaprocessnearsitsCPUtimelimitandSIGXFSZwarnsthatthelimitonfilesizecreationhasbeen reached. 2.3.3.Signalhandlers Aprocesshasahandlerassociatedwitheachsignalthatcontrolsthewaythesignalisdelivered.Thecall CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual -9- Signals #include<signal.h> structsigvec{ int(*svhandler)(); intsvmask; intsvonstack; }; sigvec(signo,sv,osv) intsigno;structsigvec*sv;resultstructsigvec*osv; assignsinterrupthandleraddresssvhandlertosignalsigno.Eachhandleraddressspecifieseither aninterruptroutineforthesignal,thatthesignalistobeignored,orthatadefaultaction(usuallyprocesstermination)istooccurifthesignaloccurs.TheconstantsSIGIGNandSIGDEF usedasvaluesforsvhandlercauseignoringordefaultingofacondition.Thesvmaskand svonstackvaluesspecifythesignalmasktobeusedwhenthehandlerisinvokedandwhetherthe handlershouldoperateonthenormalrun-timestackoraspecialsignalstack(seebelow).Ifosv isnon-zero,theprevioussignalvectorisreturned. Whenasignalconditionarisesforaprocess,thesignalisaddedtoasetofsignalspending fortheprocess.Ifthesignalisnotcurrentlyblockedbytheprocessthenitwillbedelivered.The processofsignaldeliveryaddsthesignaltobedeliveredandthosesignalsspecifiedintheassociatedsignalhandler’ssvmasktoasetofthosemaskedfortheprocess,savesthecurrentprocess context,andplacestheprocessinthecontextofthesignalhandlingroutine.Thecallisarranged sothatifthesignalhandlingroutineexitsnormallythesignalmaskwillberestoredandtheprocesswillresumeexecutionintheoriginalcontext.Iftheprocesswishestoresumeinadifferent context,thenitmustarrangetorestorethesignalmaskitself. Themaskofblockedsignalsisindependentofhandlersforsignals.Itpreventssignalsfrom beingdeliveredmuchasaraisedhardwareinterruptprioritylevelpreventshardwareinterrupts. Preventinganinterruptfromoccurringbychangingthehandlerisanalogoustodisablingadevice fromfurtherinterrupts. ThesignalhandlingroutinesvhandleriscalledbyaCcalloftheform (*svhandler)(signo,code,scp); intsigno;longcode;structsigcontext*scp; Thesignogivesthenumberofthesignalthatoccurred,andthecode,awordofinformationsuppliedbythehardware.Thescpparameterisapointertoamachine-dependentstructurecontain-ingtheinformationforrestoringthecontextbeforethesignal. 2.3.4.Sendingsignals Aprocesscansendasignaltoanotherprocessorgroupofprocesseswiththecalls: kill(pid,signo) intpid,signo; killpgrp(pgrp,signo) intpgrp,signo; Unlesstheprocesssendingthesignalisprivileged,itandtheprocessreceivingthesignalmust havethesameeffectiveuserid. Signalsarealsosentimplicitlyfromaterminaldevicetotheprocessgroupassociatedwith theterminalwhencertaininputcharactersaretyped. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-10- Signals 2.3.5.Protectingcriticalsections Toblockasectionofcodeagainstoneormoresignals,asigblockcallmaybeusedtoadda setofsignalstotheexistingmask,returningtheoldmask: oldmask=sigblock(mask); resultlongoldmask;longmask; Theoldmaskcanthenberestoredlaterwithsigsetmask, oldmask=sigsetmask(mask); resultlongoldmask;longmask; Thesigblockcallcanbeusedtoreadthecurrentmaskbyspecifyinganemptymask. Itispossibletocheckconditionswithsomesignalsblocked,andthentopausewaitingfora signalandrestoringthemask,byusing: sigpause(mask); longmask; 2.3.6.Signalstacks Applicationsthatmaintaincomplexorfixedsizestackscanusethecall structsigstack{ caddrtsssp; intssonstack; }; sigstack(ss,oss) structsigstack*ss;resultstructsigstack*oss; toprovidethesystemwithastackbasedatssspfordeliveryofsignals.Thevaluessonstack indicateswhethertheprocessiscurrentlyonthesignalstack,anotionmaintainedinsoftwareby thesystem. Whenasignalistobedelivered,thesystemcheckswhethertheprocessisonasignalstack. Ifnot,thentheprocessisswitchedtothesignalstackfordelivery,withthereturnfromthesignal arrangedtorestorethepreviousstack. Iftheprocesswishestotakeanon-localexitfromthesignalroutine,orruncodefromthe signalstackthatusesadifferentstack,asigstackcallshouldbeusedtoresetthesignalstack. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-11- Timers 2.4.Timers 2.4.1.Realtime Thesystem’snotionofthecurrentGreenwichtimeandthecurrenttimezoneissetand returnedbythecallbythecalls: #include<sys/time.h> settimeofday(tvp,tzp); structtimeval*tp; structtimezone*tzp; gettimeofday(tp,tzp); resultstructtimeval*tp; resultstructtimezone*tzp; wherethestructuresaredefinedin<sys/time.h>as: structtimeval{ longtvsec;/*secondssinceJan1,1970*/ longtvusec;/*andmicroseconds*/ }; structtimezone{ inttzminuteswest;/*ofGreenwich*/ inttzdsttime;/*typeofdstcorrectiontoapply*/ }; EarlierversionsofUNIXcontainedonlya1-secondresolutionversionofthiscall,whichremains asalibraryroutine: time(tvsec) resultlong*tvsec; returningonlythetvsecfieldfromthegettimeofdaycall. 2.4.2.Intervaltime Thesystemprovideseachprocesswiththreeintervaltimers,definedin<sys/time.h>: #defineITIMERREAL0/*realtimeintervals*/ #defineITIMERVIRTUAL1/*virtualtimeintervals*/ #defineITIMERPROF2/*userandsystemvirtualtime*/ TheITIMERREALtimerdecrementsinrealtime.Itcouldbeusedbyalibraryroutineto maintainawakeupservicequeue.ASIGALRMsignalisdeliveredwhenthistimerexpires. TheITIMERVIRTUALtimerdecrementsinprocessvirtualtime.Itrunsonlywhenthe processisexecuting.ASIGVTALRMsignalisdeliveredwhenitexpires. TheITIMERPROFtimerdecrementsbothinprocessvirtualtimeandwhenthesystemis runningonbehalfoftheprocess.Itisdesignedtobeusedbyprocessestostatisticallyprofile theirexecution.ASIGPROFsignalisdeliveredwhenitexpires. Atimervalueisdefinedbytheitimervalstructure: structitimerval{ structtimevalitinterval;/*timerinterval*/ structtimevalitvalue;/*currentvalue*/ }; CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-12- Timers andatimerissetorreadbythecall: getitimer(which,value); intwhich;resultstructitimerval*value; setitimer(which,value,ovalue); intwhich;structitimerval*value;resultstructitimerval*ovalue; Thethirdargumenttosetitimerspecifiesanoptionalstructuretoreceivethepreviouscontentsof theintervaltimer.Atimercanbedisabledbyspecifyingatimervalueof0. Thesystemroundsargumenttimerintervalstobenotlessthantheresolutionofitsclock. Thisclockresolutioncanbedeterminedbyloadingaverysmallvalueintoatimerandreading thetimerbacktoseewhatvalueresulted. ThealarmsystemcallofearlierversionsofUNIXisprovidedasalibraryroutineusingthe ITIMERREALtimer.TheprocessprofilingfacilitiesofearlierversionsofUNIXremainbecause itisnotalwayspossibletoguaranteetheautomaticrestartofsystemcallsafterreceiptofasignal. profil(buf,bufsize,offset,scale); resultchar*buf;intbufsize,offset,scale; CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-13- Descriptors 2.5.Descriptors 2.5.1.Thereferencetable Eachprocesshasaccesstoresourcesthroughdescriptors.Eachdescriptorisahandleallowingtheprocesstoreferenceobjectssuchasfiles,devicesandcommunicationslinks. Ratherthanallowingprocessesdirectaccesstodescriptors,thesystemintroducesalevelof indirection,sothatdescriptorsmaybesharedbetweenprocesses.Eachprocesshasadescriptor referencetable,containingpointerstotheactualdescriptors.Thedescriptorsthemselvesthus havemultiplereferences,andarereferencecountedbythesystem. Eachprocesshasafixedsizedescriptorreferencetable,wherethesizeisreturnedbythegetdtablesizecall: nds=getdtablesize(); resultintnds; andguaranteedtobeatleast20.Theentriesinthedescriptorreferencetablearereferredtoby smallintegers;forexampleifthereare20slotstheyarenumbered0to19. 2.5.2.Descriptorproperties Eachdescriptorhasalogicalsetofpropertiesmaintainedbythesystemanddefinedbyits type.Eachtypesupportsasetofoperations;someoperations,suchasreadingandwriting,are commontoseveralabstractions,whileothersareunique.Thegenericoperationsapplyingto manyofthesetypesaredescribedinsection2.1.Namingcontexts,filesanddirectoriesare describedinsection2.2.Section2.3describescommunicationsdomainsandsockets.Terminals and(structuredandunstructured)devicesaredescribedinsection2.4. 2.5.3.Managingdescriptorreferences Aduplicateofadescriptorreferencemaybemadebydoing new=dup(old); resultintnew;intold; returningacopyofdescriptorreferenceoldindistinguishablefromtheoriginal.Thenewchosen bythesystemwillbethesmallestunuseddescriptorreferenceslot.Acopyofadescriptorreferencemaybemadeinaspecificslotbydoing dup2(old,new); intold,new; Thedup2callcausesthesystemtodeallocatethedescriptorreferencecurrentoccupyingslotnew, ifany,replacingitwithareferencetothesamedescriptorasold.Thisdeallocationisalsoperformedby: close(old); intold; 2.5.4.Multiplexingrequests Thesystemprovidesastandardwaytodosynchronousandasynchronousmultiplexingof operations. Synchronousmultiplexingisperformedbyusingtheselectcall: nds=select(nd,in,out,except,tvp); resultintnds;intnd;result*in,*out,*except; structtimeval*tvp; Theselectcallexaminesthedescriptorsspecifiedbythesetsin,outandexcept,replacingthe CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-14- Descriptors specifiedbitmasksbythesubsetsthatselectforinput,output,andexceptionalconditionsrespectively(ndindicatesthesize,inbytes,ofthebitmasks).Ifanydescriptorsmeetthefollowingcriteria,thenthenumberofsuchdescriptorsisreturnedinndsandthebitmasksareupdated. •Adescriptorselectsforinputifaninputorientedoperationsuchasreadorreceiveispossible,orifaconnectionrequestmaybeaccepted(seesection2.3.1.4). •Adescriptorselectsforoutputifanoutputorientedoperationsuchaswriteorsendispossible,orifanoperationthatwas‘‘inprogress’’,suchasconnectionestablishment,hascompleted(seesection2.1.3). •AdescriptorselectsforanexceptionalconditionifaconditionthatwouldcauseaSIGURG signaltobegeneratedexists(seesection1.3.2). Ifnoneofthespecifiedconditionsistrue,theoperationblocksforatmosttheamountoftime specifiedbytvp,orwaitsforoneoftheconditionstoariseiftvpisgivenas0. Optionsaffectingi/oonadescriptormaybereadandsetbythecall: dopt=fcntl(d,cmd,arg) resultintdopt;intd,cmd,arg; /*interestingvaluesforcmd*/ #defineFSETFL3/*setdescriptoroptions*/ #defineFGETFL4/*getdescriptoroptions*/ #defineFSETOWN5/*setdescriptorowner(pid/pgrp)*/ #defineFGETOWN6/*getdescriptorowner(pid/pgrp)*/ TheFSETFLcmdmaybeusedtosetadescriptorinnon-blockingi/omodeand/orenablesig-nallingwheni/oispossible.FSETOWNmaybeusedtospecifyaprocessorprocessgrouptobe signalledwhenusingthelattermodeofoperation. Operationsonnon-blockingdescriptorswilleithercompleteimmediately,noteanerror EWOULDBLOCK,partiallycompleteaninputoroutputoperationreturningapartialcount,or returnanerrorEINPROGRESSnotingthattherequestedoperationisinprogress.Adescriptor whichhassignallingenabledwillcausethespecifiedprocessand/orprocessgroupbesignaled, withaSIGIOforinput,output,orin-progressoperationcomplete,oraSIGURGforexceptional conditions. Forexample,whenwritingtoaterminalusingnon-blockingoutput,thesystemwillaccept onlyasmuchdataasthereisbufferspaceforandreturn;whenmakingaconnectiononasocket, theoperationmayreturnindicatingthattheconnectionestablishmentis‘‘inprogress’’.Theselect facilitycanbeusedtodeterminewhenfurtheroutputispossibleontheterminal,orwhenthe connectionestablishmentattemptiscomplete. 2.5.5.Descriptorwrapping.† Auserprocessmaybuilddescriptorsofaspecifiedtypebywrappingacommunications channelwithasystemsuppliedprotocoltranslator: new=wrap(old,proto) resultintnew;intold;structdprop*proto; Operationsonthedescriptoroldarethentranslatedbythesystemprovidedprotocoltranslator intorequestsontheunderylingobjectoldinawaydefinedbytheprotocol.Theprotocolssupportedbythekernelmayvaryfromsystemtosystemandaredescribedintheprogrammersmanual. Protocolsmaybebasedoncommunicationsmultiplexingorarights-passingstyleofhan-dlingmultiplerequestsmadeonthesameobject.Forinstance,aprotocolforimplementingafile abstractionmayormaynotincludelocallygenerated‘‘read-ahead’’requests.Aprotocolthat †Thefacilitiesdescribedinthissectionarenotincludedin4.2BSD. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-15- Descriptors providesforread-aheadmayprovidehigherperformancebuthaveamoredifficultimplementation. Anotherexampleistheterminaldrivingfacilities.Normallyaterminalisassociatedwitha communicationslineandtheterminaltypeandstandardterminalaccessprotocoliswrapped aroundasynchronouscommunicationslineandgiventotheuser.Ifavirtualterminalisrequired, theterminaldrivercanbewrappedaroundacommunicationslink,theotherendofwhichisheld byavirtualterminalprotocolinterpreter. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-16- Resourcecontrols 2.6.Resourcecontrols 2.6.1.Processpriorities ThesystemgivesCPUschedulingprioritytoprocessesthathavenotusedCPUtime recently.Thistendstofavorinteractiveprocessesandprocessesthatexecuteonlyforshortperiods.Itispossibletodeterminetheprioritycurrentlyassignedtoaprocess,processgroup,orthe processesofaspecifieduser,ortoalterthispriorityusingthecalls: #definePRIOPROCESS0/*process*/ #definePRIOPGRP1/*processgroup*/ #definePRIOUSER2/*userid*/ prio=getpriority(which,who); resultintprio;intwhich,who; setpriority(which,who,prio); intwhich,who,prio; Thevalueprioisintherange−20to20.Thedefaultpriorityis0;lowerprioritiescausemore favorableexecution.Thegetprioritycallreturnsthehighestpriority(lowestnumericalvalue) enjoyedbyanyofthespecifiedprocesses.Thesetprioritycallsetstheprioritiesofallofthespecifiedprocessestothespecifiedvalue.Onlythesuper-usermaylowerpriorities. 2.6.2.Resourceutilization Theresourcesusedbyaprocessarereturnedbyagetrusagecall,returninginformationina structuredefinedin<sys/resource.h>: #defineRUSAGESELF0/*usagebythisprocess*/ #defineRUSAGECHILDREN-1/*usagebyallchildren*/ getrusage(who,rusage) intwho;resultstructrusage*rusage; structrusage{ structtimevalruutime;/*usertimeused*/ structtimevalrustime;/*systemtimeused*/ intrumaxrss;/*maximumcoreresidentsetsize:kbytes*/ intruixrss;/*integralsharedmemorysize(kbytes*sec)*/ intruidrss;/*unshareddata"*/ intruisrss;/*unsharedstack"*/ intruminflt;/*page-reclaims*/ intrumajflt;/*pagefaults*/ intrunswap;/*swaps*/ intruinblock;/*blockinputoperations*/ intruoublock;/*blockoutput"*/ intrumsgsnd;/*messagessent*/ intrumsgrcv;/*messagesreceived*/ intrunsignals;/*signalsreceived*/ intrunvcsw;/*voluntarycontextswitches*/ intrunivcsw;/*involuntary"*/ }; Thewhoparameterspecifieswhoseresourceusageistobereturned.Theresourcesusedbythe currentprocess,orbyalltheterminatedchildrenofthecurrentprocessmayberequested. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-17- Resourcecontrols 2.6.3.Resourcelimits Theresourcesofaprocessforwhichlimitsarecontrolledbythekernelaredefinedin <sys/resource.h>,andcontrolledbythegetrlimitandsetrlimitcalls: #defineRLIMITCPU0/*cputimeinmilliseconds*/ #defineRLIMITFSIZE1/*maximumfilesize*/ #defineRLIMITDATA2/*maximumdatasegmentsize*/ #defineRLIMITSTACK3/*maximumstacksegmentsize*/ #defineRLIMITCORE4/*maximumcorefilesize*/ #defineRLIMITRSS5/*maximumresidentsetsize*/ #defineRLIMNLIMITS6 #defineRLIMINFINITY0x7fffffff structrlimit{ intrlimcur;/*current(soft)limit*/ intrlimmax;/*hardlimit*/ }; getrlimit(resource,rlp) intresource;resultstructrlimit*rlp; setrlimit(resource,rlp) intresource;structrlimit*rlp; Onlythesuper-usercanraisethemaximumlimits.Otherusersmayonlyalterrlimcur withintherangefrom0torlimmaxor(irreversibly)lowerrlimmax. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-18-Systemoperationsupport 2.7.Systemoperationsupport Unlessnotedotherwise,thecallsinthissectionarepermittedonlytoaprivilegeduser. 2.7.1.Bootstrapoperations Thecall mount(blkdev,dir,ronly); char*blkdev,*dir;intronly; extendstheUNIXnamespace.ThemountcallspecifiesablockdeviceblkdevcontainingaUNIX filesystemtobemadeavailablestartingatdir.Ifronlyissetthenthefilesystemisread-only; writestothefilesystemwillnotbepermittedandaccesstimeswillnotbeupdatedwhenfilesare referenced.Dirisnormallyanameintherootdirectory. Thecall swapon(blkdev,size); char*blkdev;intsize; specifiesadevicetobemadeavailableforpagingandswapping. 2.7.2.Shutdownoperations Thecall unmount(dir); char*dir; unmountsthefilesystemmountedondir.Thiscallwillsucceedonlyifthefilesystemisnotcurrentlybeingused. Thecall sync(); schedulesinput/outputtocleanallsystembuffercaches.(Thiscalldoesnotrequirepriveleged status.) Thecall reboot(how) inthow; causesamachinehaltorreboot.Thecallmayrequestarebootbyspecifyinghowas RBAUTOBOOT,orthatthemachinebehaltedwithRBHALT.Theseconstantsaredefinedin <sys/reboot.h>. 2.7.3.Accounting Thesystemoptionallykeepsanaccountingrecordinafileforeachprocessthatexitsonthe system.Theformatofthisrecordisbeyondthescopeofthisdocument.Theaccountingmaybe enabledtoafilenamebydoing acct(path); char*path; Ifpathisnull,thenaccountingisdisabled.Otherwise,thenamedfilebecomestheaccountingfile. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-19- Systemfacilities 3.Systemfacilities Thissectiondiscussesthesystemfacilitiesthatarenotconsideredpartofthekernel. Thesystemabstractionsdescribedare: Directorycontexts AdirectorycontextisapositionintheUNIXfilesystemnamespace.Operationsonfiles andothernamedobjectsinafilesystemarealwaysspecifiedrelativetosuchacontext. Files Filesareusedtostoreuninterpretedsequenceofbytesonwhichrandomaccessreadsand writesmayoccur.Pagesfromfilesmayalsobemappedintoprocessaddressspace.Adirectorymaybereadasafile†. Communicationsdomains Acommunicationsdomainrepresentsaninterprocesscommunicationsenvironment,suchas thecommunicationsfacilitiesoftheUNIXsystem,communicationsintheINTERNET,or theresourcesharingprotocolsandaccessrightsofaresourcesharingsystemonalocalnetwork. Sockets AsocketisanendpointofcommunicationandthefocalpointforIPCinacommunications domain.Socketsmaybecreatedinpairs,orgivennamesandusedtorendezvouswithother socketsinacommunicationsdomain,acceptingconnectionsfromthesesocketsorexchanging messageswiththem.Theseoperationsmodelalabeledorunlabeledcommunicationsgraph, andcanbeusedinawidevarietyofcommunicationsdomains.Socketscanhavedifferent typestoprovidedifferentsemanticsofcommunication,increasingtheflexibilityofthe model. Terminalsandotherdevices Devicesincludeterminals,providinginputeditingandinterruptgenerationandoutputflow controlandediting,magnetictapes,disksandotherperipherals.Theyoftensupportthe genericreadandwriteoperationsaswellasanumberofioctls. Processes Processdescriptorsprovidefacilitiesforcontrolanddebuggingofotherprocesses. †Supportformappingfilesisnotincludedinthe4.2release. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-20- Genericoperations 3.1.Genericoperations Manysystemabstractionssupporttheoperationsread,writeandioctl.Wedescribethe basicsofthesecommonprimitiveshere.Similarly,themechanismswherebynormallysynchronous operationsmayoccurinanon-blockingorasynchronousfashionarecommontoallsystem-defined abstractionsandaredescribedhere. 3.1.1.Readandwrite Thereadandwritesystemcallscanbeappliedtocommunicationschannels,files,terminals anddevices.Theyhavetheform: cc=read(fd,buf,nbytes); resultintcc;intfd;resultcaddrtbuf;intnbytes; cc=write(fd,buf,nbytes); resultintcc;intfd;caddrtbuf;intnbytes; Thereadcalltransfersasmuchdataaspossiblefromtheobjectdefinedbyfdtothebufferat addressbufofsizenbytes.Thenumberofbytestransferredisreturnedincc,whichis−1ifa returnoccurredbeforeanydatawastransferredbecauseofanerrororuseofnon-blockingopera-tions. Thewritecalltransfersdatafromthebuffertotheobjectdefinedbyfd.Dependingonthe typeoffd,itispossiblethatthewritecallwillacceptsomeportionoftheprovidedbytes;theuser shouldresubmittheotherbytesinalaterrequestinthiscase.Errorreturnsbecauseofinterruptedorotherwiseincompleteoperationsarepossible. Scatteringofdataoninputorgatheringofdataforoutputisalsopossibleusinganarrayof input/outputvectordescriptors.Thetypeforthedescriptorsisdefinedin<sys/uio.h>as: structiovec{ caddrtiovmsg;/*baseofacomponent*/ intiovlen;/*lengthofacomponent*/ }; Thecallsusinganarrayofdescriptorsare: cc=readv(fd,iov,iovlen); resultintcc;intfd;structiovec*iov;intiovlen; cc=writev(fd,iov,iovlen); resultintcc;intfd;structiovec*iov;intiovlen; Hereiovlenisthecountofelementsintheiovarray. 3.1.2.Input/outputcontrol Controloperationsonanobjectareperformedbytheioctloperation: ioctl(fd,request,buffer); intfd,request;caddrtbuffer; Thisoperationcausesthespecifiedrequesttobeperformedontheobjectfd.Therequestparameterspecifieswhethertheargumentbufferistoberead,written,readandwritten,orisnot needed,andalsothesizeofthebuffer,aswellastherequest.Differentdescriptortypesandsubtypeswithindescriptortypesmayusedistinctioctlrequests.Forexample,operationsonterminalscontrolflushingofinputandoutputqueuesandsettingofterminalparameters;operationson diskscauseformattingoperationstooccur;operationsontapescontroltapepositioning. Thenamesforbasiccontroloperationsaredefinedin<sys/ioctl.h>. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-21- Genericoperations 3.1.3.Non-blockingandasynchronousoperations Aprocessthatwishestodonon-blockingoperationsononeofitsdescriptorssetsthe descriptorinnon-blockingmodeasdescribedinsection1.5.4.Thereafterthereadcallwillreturn aspecificEWOULDBLOCKerrorindicationifthereisnodatatoberead.Theprocessmaydselecttheassociateddescriptortodeterminewhenareadispossible. Outputattemptedwhenadescriptorcanacceptlessthanisrequestedwilleitheraccept someoftheprovideddata,returningashorterthannormallength,orreturnanerrorindicating thattheoperationwouldblock.Moreoutputcanbeperformedassoonasaselectcallindicates theobjectiswriteable. Operationsotherthandatainputoroutputmaybeperformedonadescriptorinanonblockingfashion.Theseoperationswillreturnwithacharacteristicerrorindicatingthattheyare inprogressiftheycannotreturnimmediately.Thedescriptormaythenbeselectedforwriteto findoutwhentheoperationcanberetried.Whenselectindicatesthedescriptoriswriteable,a respecificationoftheoriginaloperationwillreturntheresultoftheoperation. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-22- Filesystem 3.2.Filesystem 3.2.1.Overview Thefilesystemabstractionprovidesaccesstoahierarchicalfilesystemstructure.Thefile systemcontainsdirectories(eachofwhichmaycontainothersub-directories)aswellasfilesand referencestootherobjectssuchasdevicesandinter-processcommunicationssockets. Eachfileisorganizedasalineararrayofbytes.Norecordboundariesorsystemrelated informationispresentinafile.Filesmaybereadandwritteninarandom-accessfashion.The usermayreadthedatainadirectoryasthoughitwereanordinaryfiletodeterminethenamesof thecontainedfiles,butonlythesystemmaywriteintothedirectories.Thefilesystemstoresonly asmallamountofownership,protectionandusageinformationwithafile. 3.2.2.Naming Thefilesystemcallstakepathnamearguments.Theseconsistofazeroormorecomponent filenamesseparatedby‘‘/’’characters,whereeachfilenameisupto255ASCIIcharacters excludingnulland‘‘/’’. Eachprocessalwayshastwonamingcontexts:onefortherootdirectoryofthefilesystem andoneforthecurrentworkingdirectory.Theseareusedbythesysteminthefilenametranslationprocess.Ifapathnamebeginswitha‘‘/’’,itiscalledafullpathnameandinterpretedrelativetotherootdirectorycontext.Ifthepathnamedoesnotbeginwitha‘‘/’’itiscalledarelativepathnameandinterpretedrelativetothecurrentdirectorycontext. Thesystemlimitsthetotallengthofapathnameto1024characters. Thefilename‘‘..’’ineachdirectoryreferstotheparentdirectoryofthatdirectory.Theparentdirectoryofafilesystemisalwaysthesystemsrootdirectory. Thecalls chdir(path); char*path; chroot(path) char*path; changethecurrentworkingdirectoryandrootdirectorycontextofaprocess.Onlythesuper-user canchangetherootdirectorycontextofaprocess. 3.2.3.Creationandremoval Thefilesystemallowsdirectories,files,specialdevices,and‘‘portals’’tobecreatedand removedfromthefilesystem. 3.2.3.1.Directorycreationandremoval Adirectoryiscreatedwiththemkdirsystemcall: mkdir(path,mode); char*path;intmode; andremovedwiththermdirsystemcall: rmdir(path); char*path; Adirectorymustbeemptyifitistobedeleted. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-23- Filesystem 3.2.3.2.Filecreation Filesarecreatedwiththeopensystemcall, fd=open(path,oflag,mode); resultintfd;char*path;intoflag,mode; Thepathparameterspecifiesthenameofthefiletobecreated.Theoflagparametermustinclude OCREATfrombelowtocausethefiletobecreated.Theprotectionforthenewfileisspecified inmode.Bitsforoflagaredefinedin<sys/file.h>: #defineORDONLY000/*openforreading*/ #defineOWRONLY001/*openforwriting*/ #defineORDWR002/*openforread&write*/ #defineONDELAY004/*non-blockingopen*/ #defineOAPPEND010/*appendoneachwrite*/ #defineOCREAT01000/*openwithfilecreate*/ #defineOTRUNC02000/*openwithtruncation*/ #defineOEXCL04000/*erroroncreateiffileexists*/ OneofORDONLY,OWRONLYandORDWRshouldbespecified,indicatingwhattypes ofoperationsaredesiredtobeperformedontheopenfile.Theoperationswillbecheckedagainst theuser’saccessrightstothefilebeforeallowingtheopentosucceed.SpecifyingOAPPEND causeswritestoautomaticallyappendtothefile.TheflagOCREATcausesthefiletobecreatedifitdoesnotexist,withthespecifiedmode,ownedbythecurrentuserandthegroupofthe containingdirectory. IftheopenspecifiestocreatethefilewithOEXCLandthefilealreadyexists,thenthe openwillfailwithoutaffectingthefileinanyway.Thisprovidesasimpleexclusiveaccessfacility. 3.2.3.3.Creatingreferencestodevices Thefilesystemallowsentrieswhichreferenceperipheraldevices.Peripheralsaredistinguishedasblockorcharacterdevicesaccordingbytheirabilitytosupportblock-orientedopera-tions.Devicesareidentifiedbytheir‘‘major’’and‘‘minor’’devicenumbers.Themajordevice numberdeterminesthekindofperipheralitis,whiletheminordevicenumberindicatesoneof possiblymanyperipheralsofthatkind.Structureddeviceshavealloperationsperformedinternallyin‘‘block’’quantitieswhileunstructureddevicesoftenhaveanumberofspecialioctloperations,andmayhaveinputandoutputperformedinlargeunits.Themknodcallcreatesspecial entries: mknod(path,mode,dev); char*path;intmode,dev; wheremodeisformedfromtheobjecttypeandaccesspermissions.Theparameterdevisaconfigurationdependentparameterusedtoidentifyspecificcharacterorblocki/odevices. 3.2.3.4.Portalcreation† Thecall fd=portal(name,server,param,dtype,protocol,domain,socktype) resultintfd;char*name,*server,*param;intdtype,protocol; intdomain,socktype; placesanameinthefilesystemnamespacethatcausesconnectiontoaserverprocesswhenthe nameisused.Theportalcallreturnsanactiveportalinfdasthoughanaccesshadoccurredto activateaninactiveportal,asnowdescribed. †Theportalcallisnotimplementedin4.2BSD. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-24- Filesystem Whenaninactiveportalisaccesseed,thesystemsetsupasocketofthespecifiedsocktypein thespecifiedcommunicationsdomain(seesection2.3),andcreatestheserverprocess,givingit thespecifiedparamasargumenttohelpitidentifytheportal,andalsogivingitthenewlycreated socketasdescriptornumber0.Theaccessoroftheportalwillcreateasocketinthesamedomain andconnecttotheserver.Theuserwillthenwrapthesocketinthespecifiedprotocoltocreatean objectoftherequireddescriptortypedtypeandproceedwiththeoperationwhichwasinprogress beforetheportalwasencountered. Whiletheserverprocessholdsthesocket(whichitreceivedasfdfromtheportalcallon descriptor0atactivation)furtherreferenceswillresultinconnectionsbeingmadetothesame socket. 3.2.3.5.File,device,andportalremoval Areferencetoafile,specialdeviceorportalmayberemovedwiththeunlinkcall, unlink(path); char*path; Thecallermusthavewriteaccesstothedirectoryinwhichthefileislocatedforthiscalltobe successful. 3.2.4.Readingandmodifyingfileattributes Detailedinformationabouttheattributesofafilemaybeobtainedwiththecalls: #include<sys/stat.h> stat(path,stb); char*path;resultstructstat*stb; fstat(fd,stb); intfd;resultstructstat*stb; Thestatstructureincludesthefiletype,protection,ownership,accesstimes,size,andacountof hardlinks.Ifthefileisasymboliclink,thenthestatusofthelinkitself(ratherthanthefilethe linkreferences)maybefoundusingthelstatcall: lstat(path,stb); char*path;resultstructstat*stb; Newlycreatedfilesareassignedtheuseridoftheprocessthatcreateditandthegroupidof thedirectoryinwhichitwascreated.Theownershipofafilemaybechangedbyeitherofthe calls chown(path,owner,group); char*path;intowner,group; fchown(fd,owner,group); intfd,owner,group; Inadditiontoownership,eachfilehasthreelevelsofaccessprotectionassociatedwithit. Theselevelsareownerrelative,grouprelative,andglobal(allusersandgroups).Eachlevelof accesshasseparateindicatorsforreadpermission,writepermission,andexecutepermission.The protectionbitsassociatedwithafilemaybesetbyeitherofthecalls: CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-25- Filesystem chmod(path,mode); char*path;intmode; fchmod(fd,mode); intfd,mode; wheremodeisavalueindicatingthenewprotectionofthefile.Thefilemodeisathreedigit octalnumber.Eachdigitencodesreadaccessas4,writeaccessas2andexecuteaccessas1,or’ed together.The0700bitsdescribeowneraccess,the070bitsdescribetheaccessrightsforprocesses inthesamegroupasthefile,andthe07bitsdescribetheaccessrightsforotherprocesses. Finally,theaccessandmodifytimesonafilemaybesetbythecall: utimes(path,tvp) char*path;structtimeval*tvp[2]; Thisisparticularlyusefulwhenmovingfilesbetweenmedia,topreserverelationshipsbetweenthe timesthefilewasmodified. 3.2.5.Linksandrenaming Linksallowmultiplenamesforafiletoexist.Linksexistindependentlyofthefilelinkedto. Twotypesoflinksexist,hardlinksandsymboliclinks.Ahardlinkisareferencecounting mechanismthatallowsafiletohavemultiplenameswithinthesamefilesystem.Symboliclinks causestringsubstitutionduringthepathnameinterpretationprocess. Hardlinksandsymboliclinkshavedifferentproperties.Ahardlinkinsuresthetargetfile willalwaysbeaccessible,evenafteritsoriginaldirectoryentryisremoved;nosuchguarantee existsforasymboliclink.Symboliclinkscanspanfilesystemsboundaries. Thefollowingcallscreateanewlink,namedpath2,topath1: link(path1,path2); char*path1,*path2; symlink(path1,path2); char*path1,*path2; Theunlinkprimitivemaybeusedtoremoveeithertypeoflink. Ifafileisasymboliclink,the‘‘value’’ofthelinkmaybereadwiththereadlinkcall, len=readlink(path,buf,bufsize); resultintlen;resultchar*path,*buf;intbufsize; Thiscallreturns,inbuf,thenull-terminatedstringsubstitutedintopathnamespassingthrough path. Atomicrenamingoffilesystemresidentobjectsispossiblewiththerenamecall: rename(oldname,newname); char*oldname,*newname; wherebotholdnameandnewnamemustbeinthesamefilesystem.Ifnewnameexistsandisa directory,thenitmustbeempty. 3.2.6.Extensionandtruncation Filesarecreatedwithzerolengthandmaybeextendedsimplybywritingorappendingto them.Whileafileisopenthesystemmaintainsapointerintothefileindicatingthecurrentlocationinthefileassociatedwiththedescriptor.Thispointermaybemovedaboutinthefileina randomaccessfashion.Tosetthecurrentoffsetintoafile,thelseekcallmaybeused, CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-26- Filesystem oldoffset=lseek(fd,offset,type); resultofftoldoffset;intfd;offtoffset;inttype; wheretypeisgivenin<sys/file.h>asoneof, #defineLSET0/*setabsolutefileoffset*/ #defineLINCR1/*setfileoffsetrelativetocurrentposition*/ #defineLXTND2/*setoffsetrelativetoend-of-file*/ Thecall‘‘lseek(fd,0,LINCR)’’returnsthecurrentoffsetintothefile. Filesmayhave‘‘holes’’inthem.Holesarevoidareasinthelinearextentofthefilewhere datahasneverbeenwritten.Thesemaybecreatedbyseekingtoalocationinafilepastthecurrentend-of-fileandwriting.Holesaretreatedbythesystemaszerovaluedbytes. Afilemaybetruncatedwitheitherofthecalls: truncate(path,length); char*path;intlength; ftruncate(fd,length); intfd,length; reducingthesizeofthespecifiedfiletolengthbytes. 3.2.7.Checkingaccessibility Aprocessrunningwithdifferentrealandeffectiveuseridsmayinterrogatetheaccessibility ofafiletotherealuserbyusingtheaccesscall: accessible=access(path,how); resultintaccessible;char*path;inthow; Herehowisconstructedbyor’ingthefollowingbits,definedin<sys/file.h>: #defineFOK0/*fileexists*/ #defineXOK1/*fileisexecutable*/ #defineWOK2/*fileiswritable*/ #defineROK4/*fileisreadable*/ Thepresenceorabsenceofadvisorylocksdoesnotaffecttheresultofaccess. 3.2.8.Locking Thefilesystemprovidesbasicfacilitiesthatallowcooperatingprocessestosynchronizetheir accesstosharedfiles.Aprocessmayplaceanadvisoryreadorwritelockonafile,sothatother cooperatingprocessesmayavoidinterferingwiththeprocess’access.Thissimplemechanismprovideslockingwithfilegranularity.MoregranularlockingcanbebuiltusingtheIPCfacilitiesto providealockmanager.Thesystemdoesnotforceprocessestoobeythelocks;theyareofan advisorynatureonly. Lockingisperformedafteranopencallbyapplyingtheflockprimitive, flock(fd,how); intfd,how; wherethehowparameterisformedfrombitsdefinedin<sys/file.h>: #defineLOCKSH1/*sharedlock*/ #defineLOCKEX2/*exclusivelock*/ #defineLOCKNB4/*don’tblockwhenlocking*/ #defineLOCKUN8/*unlock*/ Successivelockcallsmaybeusedtoincreaseordecreasetheleveloflocking.Ifanobjectiscurrentlylockedbyanotherprocesswhenaflockcallismade,thecallerwillbeblockeduntilthe CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-27- Filesystem currentlockownerreleasesthelock;thismaybeavoidedbyincludingLOCKNBinthehow parameter.SpecifyingLOCKUNremovesalllocksassociatedwiththedescriptor.Advisory locksheldbyaprocessareautomaticallydeletedwhentheprocessterminates. 3.2.9.Diskquotas Asanoptionalfacility,eachfilesystemmayberequestedtoimposelimitsonauser’sdisk usage.Twoquantitiesarelimited:thetotalamountofdiskspacewhichausermayallocateina filesystemandthetotalnumberoffilesausermaycreateinafilesystem.Quotasareexpressed ashardlimitsandsoftlimits.Ahardlimitisalwaysimposed;ifauserwouldexceedahardlimit, theoperationwhichcausedtheresourcerequestwillfail.Asoftlimitresultsintheuserreceiving awarningmessage,butwithallocationsucceeding.Facilitiesareprovidedtoturnsoftlimitsinto hardlimitsifauserhasexceededasoftlimitforanunreasonableperiodoftime. Toenablediskquotasonafilesystemthesetquotacallisused: setquota(special,file) char*special,*file; wherespecialreferstoastructureddevicefilewhereamountedfilesystemexists,andfilerefersto adiskquotafile(residingonthefilesystemassociatedwithspecial)fromwhichuserquotas shouldbeobtained.Theformatofthediskquotafileisimplementationdependent. Tomanipulatediskquotasthequotacallisprovided: #include<sys/quota.h> quota(cmd,uid,arg,addr) intcmd,uid,arg;caddrtaddr; TheindicatedcmdisappliedtotheuserIDuid.Theparametersargandaddrarecommandspecific.Thefile<sys/quota.h>containsdefinitionspertinenttotheuseofthiscall. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-28-Interprocesscommunications 3.3.Interprocesscommunications 3.3.1.Interprocesscommunicationprimitives 3.3.1.1.Communicationdomains Thesystemprovidesaccesstoanextensiblesetofcommunicationdomains.Acommunicationdomainisidentifiedbyamanifestconstantdefinedinthefile<sys/socket.h>.Important standarddomainssupportedbythesystemarethe‘‘unix’’domain,AFUNIX,forcommunication withinthesystem,andthe‘‘internet’’domainforcommunicationintheDARPAinternet, AFINET.Otherdomainscanbeaddedtothesystem. 3.3.1.2.Sockettypesandprotocols Withinadomain,communicationtakesplacebetweencommunicationendpointsknownas sockets.Eachsockethasthepotentialtoexchangeinformationwithothersocketswithinthe domain. Eachsockethasanassociatedabstracttype,whichdescribesthesemanticsofcommunicationusingthatsocket.Propertiessuchasreliability,ordering,andpreventionofduplicationof messagesaredeterminedbythetype.Thebasicsetofsockettypesisdefinedin<sys/socket.h>: /*Standardsockettypes*/ #defineSOCKDGRAM1/*datagram*/ #defineSOCKSTREAM2/*virtualcircuit*/ #defineSOCKRAW3/*rawsocket*/ #defineSOCKRDM4/*reliably-deliveredmessage*/ #defineSOCKSEQPACKET5/*sequencedpackets*/ TheSOCKDGRAMtypemodelsthesemanticsofdatagramsinnetworkcommunication:messagesmaybelostorduplicatedandmayarriveout-of-order.TheSOCKRDMtypemodelsthe semanticsofreliabledatagrams:messagesarriveunduplicatedandin-order,thesenderisnotified ifmessagesarelost.Thesendandreceiveoperations(describedbelow)generatereliable/unreliabledatagrams.TheSOCKSTREAMtypemodelsconnection-basedvirtualcircuits: two-waybytestreamswithnorecordboundaries.TheSOCKSEQPACKETtypemodelsacon-nection-based,full-duplex,reliable,sequencedpacketexchange;thesenderisnotifiedifmessages arelost,andmessagesareneverduplicatedorpresentedout-of-order.Usersofthelasttwo abstractionsmayusethefacilitiesforout-of-bandtransmissiontosendout-of-banddata. SOCKRAWisusedforunprocessedaccesstointernalnetworklayersandinterfaces;ithas nospecificsemantics. Othersockettypescanbedefined.† Eachsocketmayhaveaconcreteprotocolassociatedwithit.Thisprotocolisusedwithin thedomaintoprovidethesemanticsrequiredbythesockettype.Forexample,withinthe‘‘internet’’domain,theSOCKDGRAMtypemaybeimplementedbytheUDPuserdatagramprotocol, andtheSOCKSTREAMtypemaybeimplementedbytheTCPtransmissioncontrolprotocol, whilenostandardprotocolstoprovideSOCKRDMorSOCKSEQPACKETsocketsexist. 3.3.1.3.Socketcreation,namingandserviceestablishment Socketsmaybeconnectedorunconnected.Anunconnectedsocketdescriptorisobtainedby thesocketcall: s=socket(domain,type,protocol); resultints;intdomain,type,protocol; †4.2BSDdoesnotsupporttheSOCKRDMandSOCKSEQPACKETtypes. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-29-Interprocesscommunications Anunconnectedsocketdescriptormayyieldaconnectedsocketdescriptorinoneoftwo ways:eitherbyactivelyconnectingtoanothersocket,orbybecomingassociatedwithanamein thecommunicationsdomainandacceptingaconnectionfromanothersocket. Toacceptconnections,asocketmustfirsthaveabindingtoanamewithinthecommunicationsdomain.Suchabindingisestablishedbyabindcall: bind(s,name,namelen); ints;char*name;intnamelen; Asocket’sboundnamemayberetrievedwithagetsocknamecall: getsockname(s,name,namelen); ints;resultcaddrtname;resultint*namelen; whilethepeer’snamecanberetrievedwithgetpeername: getpeername(s,name,namelen); ints;resultcaddrtname;resultint*namelen; Domainsmaysupportsocketswithseveralnames. 3.3.1.4.Acceptingconnections Onceabindingismade,itispossibletolistenforconnections: listen(s,backlog); ints,backlog; Thebacklogspecifiesthemaximumcountofconnectionsthatcanbesimultaneouslyqueuedawaitingacceptance. Anacceptcall: t=accept(s,name,anamelen); resultintt;ints;resultcaddrtname;resultint*anamelen; returnsadescriptorforanew,connected,socketfromthequeueofpendingconnectionsons. 3.3.1.5.Makingconnections Anactiveconnectiontoanamedsocketismadebytheconnectcall: connect(s,name,namelen); ints;caddrtname;intnamelen; Itisalsopossibletocreateconnectedpairsofsocketswithoutusingthedomain’sname spacetorendezvous;thisisdonewiththesocketpaircall†: socketpair(d,type,protocol,sv); intd,type,protocol;resultintsv[2]; Herethereturnedsvdescriptorscorrespondtothoseobtainedwithacceptandconnect. Thecall pipe(pv) resultintpv[2]; createsapairofSOCKSTREAMsocketsintheUNIXdomain,withpv[0]onlywriteableand pv[1]onlyreadable. †4.2BSDsupportssocketpaircreationonlyinthe‘‘unix’’communicationdomain. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-30-Interprocesscommunications 3.3.1.6.Sendingandreceivingdata Messagesmaybesentfromasocketby: cc=sendto(s,buf,len,flags,to,tolen); resultintcc;ints;caddrtbuf;intlen,flags;caddrtto;inttolen; ifthesocketisnotconnectedor: cc=send(s,buf,len,flags); resultintcc;ints;caddrtbuf;intlen,flags; ifthesocketisconnected.Thecorrespondingreceiveprimitivesare: msglen=recvfrom(s,buf,len,flags,from,fromlenaddr); resultintmsglen;ints;resultcaddrtbuf;intlen,flags; resultcaddrtfrom;resultint*fromlenaddr; and msglen=recv(s,buf,len,flags); resultintmsglen;ints;resultcaddrtbuf;intlen,flags; Intheunconnectedcase,theparameterstoandtolenspecifythedestinationorsourceofthe message,whilethefromparameterstoresthesourceofthemessage,and*fromlenaddrinitially givesthesizeofthefrombufferandisupdatedtoreflectthetruelengthofthefromaddress. Allcallscausethemessagetobereceivedinorsentfromthemessagebufferoflengthlen bytes,startingataddressbuf.Theflagsspecifypeekingatamessagewithoutreadingitorsendingorreceivinghigh-priorityout-of-bandmessages,asfollows: #defineMSGPEEK0x1/*peekatincomingmessage*/ #defineMSGOOB0x2/*processout-of-banddata*/ 3.3.1.7.Scatter/gatherandexchangingaccessrights Itispossiblescatterandgatherdataandtoexchangeaccessrightswithmessages.When eitheroftheseoperationsisinvolved,thenumberofparameterstothecallbecomeslarge.Thus thesystemdefinesamessageheaderstructure,in<sys/socket.h>,whichcanbeusedtoconvenientlycontaintheparameterstothecalls: structmsghdr{ caddrtmsgname;/*optionaladdress*/ intmsgnamelen;/*sizeofaddress*/ structiov*msgiov;/*scatter/gatherarray*/ intmsgiovlen;/*#elementsinmsgiov*/ caddrtmsgaccrights;/*accessrightssent/received*/ intmsgaccrightslen;/*sizeofmsgaccrights*/ }; Heremsgnameandmsgnamelenspecifythesourceordestinationaddressifthesocketisunconnected;msgnamemaybegivenasanullpointerifnonamesaredesiredorrequired.The msgiovandmsgiovlendescribethescatter/gatherlocations,asdescribedinsection2.1.3. Accessrightstobesentalongwiththemessagearespecifiedinmsgaccrights,whichhaslength msgaccrightslen.Inthe‘‘unix’’domaintheseareanarrayofintegerdescriptors,takenfromthe sendingprocessandduplicatedinthereceiver. Thisstructureisusedintheoperationssendmsgandrecvmsg: CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-31-Interprocesscommunications sendmsg(s,msg,flags); ints;structmsghdr*msg;intflags; msglen=recvmsg(s,msg,flags); resultintmsglen;ints;resultstructmsghdr*msg;intflags; 3.3.1.8.Usingreadandwritewithsockets ThenormalUNIXreadandwritecallsmaybeappliedtoconnectedsocketsandtranslated intosendandreceivecallsfromortoasingleareaofmemoryanddiscardinganyrightsreceived. Aprocessmayoperateonavirtualcircuitsocket,aterminalorafilewithblockingornonblockinginput/outputoperationswithoutdistinguishingthedescriptortype. 3.3.1.9.Shuttingdownhalvesoffull-duplexconnections Aprocessthathasafull-duplexsocketsuchasavirtualcircuitandnolongerwishestoread fromorwritetothissocketcangivethecall: shutdown(s,direction); ints,direction; wheredirectionis0tonotreadfurther,1tonotwritefurther,or2tocompletelyshuttheconnectiondown. 3.3.1.10.Socketandprotocoloptions Sockets,andtheirunderlyingcommunicationprotocols,maysupportoptions.Theseoptions maybeusedtomanipulateimplementationspecificornon-standardfacilities.Thegetsockoptand setsockoptcallsareusedtocontroloptions: getsockopt(s,level,optname,optval,optlen) ints,level,optname;resultcaddrtoptval;resultint*optlen; setsockopt(s,level,optname,optval,optlen) ints,level,optname;caddrtoptval;intoptlen; Theoptionoptnameisinterpretedattheindicatedprotocollevelforsockets.Ifavalueisspecifiedwithoptvalandoptlen,itisinterpretedbythesoftwareoperatingatthespecifiedlevel.The levelSOLSOCKETisreservedtoindicateoptionsmaintainedbythesocketfacilities.Otherlevel valuesindicateaparticularprotocolwhichistoactontheoptionrequest;thesevaluesarenormallyinterpretedasa‘‘protocolnumber’’. 3.3.2.UNIXdomain ThissectiondescribesbrieflythepropertiesoftheUNIXcommunicationsdomain. 3.3.2.1.Typesofsockets IntheUNIXdomain,theSOCKSTREAMabstractionprovidespipe-likefacilities,while SOCKDGRAMprovides(usually)reliablemessage-stylecommunications. 3.3.2.2.Naming SocketnamesarestringsandmayappearintheUNIXfilesystemnamespacethroughportals†. †The4.2BSDimplementationoftheUNIXdomainembedsboundsocketsintheUNIXfilesystem namespace;thisisasideeffectoftheimplementation. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-32-Interprocesscommunications 3.3.2.3.Accessrightstransmission TheabilitytopassUNIXdescriptorswithmessagesinthisdomainallowsmigrationofservicewithinthesystemandallowsuserprocessestobeusedinbuildingsystemfacilities. 3.3.3.INTERNETdomain ThissectiondescribesbrieflyhowtheINTERNETdomainismappedtothemodel describedinthissection.Moreinformationwillbefoundinthedocumentdescribingthenetwork implementationin4.2BSD. 3.3.3.1.Sockettypesandprotocols SOCKSTREAMissupportedbytheINTERNETTCPprotocol;SOCKDGRAMbythe UDPprotocol.TheSOCKSEQPACKEThasnodirectINTERNETfamilyanalogue;aprotocol basedononefromtheXEROXNSfamilyandlayeredontopofIPcouldbeimplementedtofill thisgap. 3.3.3.2.Socketnaming SocketsintheINTERNETdomainhavenamescomposedofthe32bitinternetaddress,and a16bitportnumber.Optionsmaybeusedtoprovidesourceroutingfortheaddress,security options,oradditionaladdressforsubnetsofINTERNETforwhichthebasic32bitaddressesare insufficient. 3.3.3.3.Accessrightstransmission NoaccessrightstransmissionfacilitiesareprovidedintheINTERNETdomain. 3.3.3.4.Rawaccess TheINTERNETdomainallowsthesuper-useraccesstotherawfacilitiesofthevariousnet-workinterfacesandthevariousinternallayersoftheprotocolimplementation.Thisallows administrativeanddebuggingfunctionstooccur.TheseinterfacesaremodeledasSOCKRAW sockets. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-33- TerminalsandDevices 3.4.TerminalsandDevices 3.4.1.Terminals Terminalssupportreadandwritei/ooperations,aswellasacollectionofterminalspecific ioctloperations,tocontrolinputcharacterediting,andoutputdelays. 3.4.1.1.Terminalinput Terminalsarehandledaccordingtotheunderlyingcommunicationcharacteristicssuchas baudrateandrequireddelays,andasetofsoftwareparameters. 3.4.1.1.1.Inputmodes Aterminalisinoneofthreepossiblemodes:raw,cbreak,orcooked.Inrawmodeallinput ispassedthroughtothereadingprocessimmediatelyandwithoutinterpretation.Incbreak mode,thehandlerinterpretsinputonlybylookingforcharactersthatcauseinterruptsoroutput flowcontrol;allothercharactersaremadeavailableasinrawmode.Incookedmode,inputis processedtoprovidestandardline-orientedlocaleditingfunctions,andinputispresentedona line-by-linebasis. 3.4.1.1.2.Interruptcharacters Interruptcharactersareinterpretedbytheterminalhandleronlyincbreakandcooked modes,andcauseasoftwareinterrupttobesenttoallprocessesintheprocessgroupassociated withtheterminal.InterruptcharactersexisttosendSIGINTandSIGQUITsignals,andtostop aprocessgroupwiththeSIGTSTPsignaleitherimmediately,orwhenallinputuptothestop characterhasbeenread. 3.4.1.1.3.Lineediting Whentheterminalisincookedmode,editingofaninputlineisperformed.Editingfacilitiesallowdeletionofthepreviouscharacterorword,ordeletionofthecurrentinputline.In addition,aspecialcharactermaybeusedtoreprintthecurrentinputlineaftersomenumberof editingoperationshavebeenapplied. Certainothercharactersareinterpretedspeciallywhenaprocessisincookedmode.The endoflinecharacterdeterminestheendofaninputrecord.Theendoffilecharactersimulates anendoffileoccurrenceonterminalinput.Flowcontrolisprovidedbystopoutputandstartoutputcontrolcharacters.Outputmaybeflushedwiththeflushoutputcharacter;andaliteralcharactermaybeusedtoforceliteralinputoftheimmediatelyfollowingcharacterintheinputline. 3.4.1.2.Terminaloutput Onoutput,theterminalhandlerprovidessomesimpleformattingservices.Theseinclude convertingthecarriagereturncharactertothetwocharacterreturn-linefeedsequence,displaying non-graphicASCIIcharactersas‘‘ˆ character’’,insertingdelaysaftercertainstandardcontrolcharacters,expandingtabs,andprovidingtranslationsforupper-caseonlyterminals. 3.4.1.3.Terminalcontroloperations Whenaterminalisfirstopeneditisinitializedtoastandardstateandconfiguredwithaset ofstandardcontrol,editing,andinterruptcharacters.Aprocessmayalterthisconfigurationwith certaincontroloperations,specifyingparametersinastandardstructure: CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-34- TerminalsandDevices structttymode{ shortttispeed;/*inputspeed*/ intttiflags;/*inputflags*/ shortttospeed;/*outputspeed*/ intttoflags;/*outputflags*/ }; and‘‘specialcharacters’’arespecifiedwiththettycharsstructure, structttychars{ chartcerasec;/*erasechar*/ chartckillc;/*eraseline*/ chartcintrc;/*interrupt*/ chartcquitc;/*quit*/ chartcstartc;/*startoutput*/ chartcstopc;/*stopoutput*/ chartceofc;/*end-of-file*/ chartcbrkc;/*inputdelimiter(likenl)*/ chartcsuspc;/*stopprocesssignal*/ chartcdsuspc;/*delayedstopprocesssignal*/ chartcrprntc;/*reprintline*/ chartcflushc;/*flushoutput(toggles)*/ chartcwerasc;/*worderase*/ chartclnextc;/*literalnextcharacter*/ }; 3.4.1.4.Terminalhardwaresupport Theterminalhandlerallowsausertoaccessbasichardwarerelatedfunctions;e.g.line speed,modemcontrol,parity,andstopbits.Aspecialsignal,SIGHUP,isautomaticallysentto processesinaterminal’sprocessgroupwhenacarriertransitionisdetected.Thisisnormally associatedwithauserhanginguponamodemcontrolledterminalline. 3.4.2.Structureddevices Structuresdevicesaretypifiedbydisksandmagnetictapes,butmayrepresentanyrandomaccessdevice.Thesystemperformsread-modify-writetypebufferingactionsonblockdevicesto allowthemtobereadandwritteninatotallyrandomaccessfashionlikeordinaryfiles.Filesystemsarenormallycreatedinblockdevices. 3.4.3.Unstructureddevices Unstructureddevicesarethosedeviceswhichdonotsupportblockstructure.Familiar unstructureddevicesarerawcommunicationslines(withnoterminalhandler),rasterplotters, magnetictapeanddisksunfetteredbybufferingandpermittinglargeblockinput/outputand positioningandformattingcommands. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-35-Processandkerneldescriptors 3.5.Processandkerneldescriptors Thestatusofthefacilitiesinthissectionisstillunderdiscussion.Theptracefacilityof 4.1BSDisprovidedin4.2BSD.Plannedenhancementswouldallowadescriptorbasedprocess controlfacility. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-36- Summaryoffacilities I.Summaryoffacilities 1.Kernelprimitives 1.1.Processnamingandprotection sethostid setUNIXhostid gethostid getUNIXhostid sethostname setUNIXhostname gethostname getUNIXhostname getpid getprocessid fork createnewprocess exit terminateaprocess execve executeadifferentprocess getuid getuserid geteuid geteffectiveuserid setreuid setrealandeffectiveuserid’s getgid getaccountinggroupid getegid geteffectiveaccountinggroupid getgroups getaccessgroupset setregid setrealandeffectivegroupid’s setgroups setaccessgroupset getpgrp getprocessgroup setpgrp setprocessgroup 1.2Memorymanagement <mman.h> memorymanagementdefinitions sbrk changedatasectionsize sstk† changestacksectionsize getpagesize getmemorypagesize mmap† mappagesofmemory mremap† remappagesinmemory munmap† unmapmemory mprotect† changeprotectionofpages madvise† givememorymanagementadvice mincore† determinecoreresidencyofpages 1.3Signals <signal.h> signaldefinitions sigvec sethandlerforsignal kill sendsignaltoprocess killpgrp sendsignaltoprocessgroup sigblock blocksetofsignals sigsetmask restoresetofblockedsignals sigpause waitforsignals sigstack setsoftwarestackforsignals 1.4Timingandstatistics <sys/time.h> time-relateddefinitions gettimeofday getcurrenttimeandtimezone settimeofday setcurrenttimeandtimezone getitimer readanintervaltimer setitimer getandsetanintervaltimer profil profileprocess 1.5Descriptors CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-37- Summaryoffacilities getdtablesize descriptorreferencetablesize dup duplicatedescriptor dup2 duplicatetospecifiedindex close closedescriptor select multiplexinput/output fcntl controldescriptoroptions wrap† wrapdescriptorwithprotocol 1.6Resourcecontrols <sys/resource.h>resource-relateddefinitions getpriority getprocesspriority setpriority setprocesspriority getrusage getresourceusage getrlimit getresourcelimitations setrlimit setresourcelimitations 1.7Systemoperationsupport mount mountadevicefilesystem swapon addaswapdevice umount umountafilesystem sync flushsystemcaches reboot rebootamachine acct specifyaccountingfile 2.Systemfacilities 2.1Genericoperations read readdata write writedata <sys/uio.h> scatter-gatherrelateddefinitions readv scattereddatainput writev gathereddataoutput <sys/ioctl.h> standardcontroloperations ioctl devicecontroloperation 2.2Filesystem Operationsmarkedwitha*existintwoforms:asshown,operatingonafilename,and operatingonafiledescriptor,whenthenameisprecededwitha‘‘f’’. <sys/file.h> filesystemdefinitions chdir changedirectory chroot changerootdirectory mkdir makeadirectory rmdir removeadirectory open openaneworexistingfile mknod makeaspecialfile portal† makeaportalentry unlink removealink stat* returnstatusforafile lstat returnedstatusoflink chown* changeowner chmod* changemode utimes changeaccess/modifytimes †Notsupportedin4.2BSD. CSRGTR/5 --September1,1982-- Joy,et.al.

4.2BSDSystemManual-38- Summaryoffacilities link makeahardlink symlink makeasymboliclink readlink readcontentsofsymboliclink rename changenameoffile lseek repositionwithinfile truncate* truncatefile access determineaccessibility flock lockafile 2.3Communications <sys/socket.h>standarddefinitions socket createsocket bind bindsockettoname getsocknamegetsocketname listen allowqueueingofconnections accept acceptaconnection connect connecttopeersocket socketpair createpairofconnectedsockets sendto senddatatonamedsocket send senddatatoconnectedsocket recvfrom receivedataonunconnectedsocket recv receivedataonconnectedsocket sendmsg sendgathereddataand/orrights recvmsg receivescattereddataand/orrights shutdown partiallyclosefull-duplexconnection getsockopt getsocketoption setsockopt setsocketoption 2.5Terminals,blockandcharacterdevices 2.4Processesandkernelhooks CSRGTR/5 --September1,1982-- Joy,et.al.