⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 p4

📁 UNIX v6源代码 这几乎是最经典的unix版本 unix操作系统设计和莱昂氏unix源代码分析都是用的该版
💻
字号:
.s16. The Shell.esFor most users,communication with \*sUNIX\*n is carried on with theaid of a program called the Shell.The Shell is a commandline interpreter: it reads lines typed by the user andinterprets them as requests to executeother programs.In simplest form, a command line consists of the commandname followed by arguments to the command, all separatedby spaces:.dccommand arg\*t\d1\u\*n arg\*t\d2\u\*n .\|.\|. arg\*t\dn\u\*n.ecThe Shell splits up the command name and the arguments intoseparate strings.Then a file with name \fIcommand\fR is sought;\fIcommand\fR may be a path name including the ``/'' character tospecify any file in the system.If \fIcommand\fR is found, it is brought intocore and executed.The argumentscollected by the Shell are accessibleto the command.When the command is finished, the Shellresumes its own execution, and indicates its readinessto accept another command by typing a prompt character..pgIf file \fIcommand\fR cannot be found,the Shell prefixes the string  \fI/\|bin/\fR  to \fIcommand\fR andattempts again to find the file.Directory \fI/\|bin\fR contains all the commandsintended to be generally used..s26.1 Standard I/O.esThe discussion of I/O in \(sc3 above seems to imply thatevery file used by a program must be opened or created by the program inorder to get a file descriptor for the file.Programs executed by the Shell, however, start off withtwo open files which have file descriptors0 and 1.As such a program begins execution, file 1 is open for writing,and is best understood as the standard output file.Except under circumstances indicated below, this fileis the user's typewriter.Thus programs which wish to write informative or diagnosticinformation ordinarily use file descriptor 1.Conversely, file 0 starts off open for reading, and programs whichwish to read messages typed by the user usuallyread this file..pgThe Shell is able to change the standard assignments ofthese file descriptors from theuser's typewriter printer and keyboard.If one of thearguments to a command is prefixed by ``>'', file descriptor1 will, for the duration of the command, refer to thefile named after the ``>''.For example,.dcls.ecordinarily lists, on the typewriter, the names of the files in the currentdirectory.The command.dcls >there.eccreates a file called \fIthere\fR and places the listing there.Thus the argument ``>there'' means, ``place output on \fIthere\fR.''On the other hand,.dced.ecordinarily enters the editor, which takes requests from theuser via his typewriter.The command.dced <script.ecinterprets \fIscript\fR as a file of editor commands;thus ``<script'' means, ``take input from \fIscript\fR.''.pgAlthough the file name following ``<'' or ``>'' appearsto be an argument to the command, in fact it is interpretedcompletely by the Shell and is not passed to thecommand at all.Thus no special coding to handle I/O redirection is needed within eachcommand; the command need merely use the standard filedescriptors 0 and 1 where appropriate..s26.2 Filters.esAn extension of the standard I/O notion is usedto direct output from one command tothe input of another.A sequence of commands separated byvertical bars causes the Shell toexecute all the commands simultaneously and to arrangethat the standard output of each commandbe delivered to the standard input ofthe next command in the sequence.Thus in the command line.dcls | pr \(mi2 | opr.ec.it lslists the names of the files in the current directory;its output is passed to \fIpr\fR,whichpaginates its input with dated headings.The argument ``\(mi2'' meansdouble column.Likewise the output from \fIpr\fR is input to \fIopr\fR.This command spools its input onto a file for off-lineprinting..pgThis procedure could have been carried outmore clumsily by.dcls >temp1.ti 1ipr \(mi2 <temp1 >temp2.ti 1iopr <temp2.ecfollowed by removal of the temporary files.In the absence of the abilityto redirect output and input,a still clumsier method would have been torequire the.it lscommandto accept user requests to paginate its output,to print in multi-column format, and to arrangethat its output be delivered off-line.Actually it would be surprising, and in factunwise for efficiency reasons,to expect authors ofcommands such as.it lsto provide such a wide variety of output options..pgA programsuch as \fIpr\fRwhich copies its standard input to its standard output(with processing)is called a \fIfilter\fR.Some filters which we have found usefulperformcharacter transliteration,sorting of the input,and encryption and decryption..s26.3 Command Separators; Multitasking.esAnother feature provided by the Shell is relatively straightforward.Commands need not be on different lines; instead they may be separatedby semicolons..dcls; ed.ecwill first list the contents of the current directory, then enterthe editor..pgA related feature is more interesting.If a command is followedby ``&'', the Shell will not wait for the command to finish beforeprompting again; instead, it is ready immediatelyto accept a new command.For example,.dcas source >output &.eccauses \fIsource\fR to be assembled, with diagnosticoutput going to \fIoutput;\fR no matter how long theassembly takes, the Shell returns immediately.When the Shell does not wait forthe completion of a command,the identification of theprocess running that command is printed.This identification may be used towait for the completion of the command or toterminate it.The ``&'' may be usedseveral times in a line:.dcas source >output & ls >files &.ecdoes both the assembly and the listing in the background.In the examples above using ``&'', an output fileother than the typewriter was provided; if this had not beendone, the outputs of the various commands would have beenintermingled..pgThe Shell also allows parentheses in the above operations.For example.dc(\|date; ls\|) >x &.ecprints the current date and time followed bya list of the current directory onto the file \fIx.\fRThe Shell also returns immediately for another request..s26.4 The Shell as a Command; Command Files.esThe Shell is itself a command, and may be called recursively.Suppose file \fItryout\fR contains the lines.dcas source.ti 1imv a.out testprog.ti 1itestprog.ecThe \fImv\fR command causes the file \fIa.out\fR to be renamed \fItestprog.\fR\fIA.out\fR is the (binary) output of the assembler, ready to be executed.Thus if the three lines above were typed on the console,\fIsource\fR would be assembled, the resulting program renamed \fItestprog\fR,and \fItestprog\fR executed.When the lines are in \fItryout\fR, the command.dcsh <tryout.ecwould cause the Shell \fIsh\fR to execute the commandssequentially..pgThe Shell has further capabilities, including theability to substitute parametersandto construct argument lists from a specifiedsubset of the file names in a directory.It is also possible toexecute commands conditionally on character string comparisonsor on existence of given filesand to perform transfers of controlwithin filed command sequences..s26.5 Implementation of the Shell.esThe outline of the operation of the Shell can now be understood.Most of the time, the Shellis waiting for the user to type a command.When thenew-line character ending the lineis typed, the Shell's \fIread\fR call returns.The Shell analyzes the command line, putting thearguments in a form appropriate for \fIexecute\fR.Then \fIfork\fR is called.The child process, whose codeof course is still that of the Shell, attemptsto perform an \fIexecute\fR with the appropriate arguments.If successful, this will bring in and start execution of the program whose namewas given.Meanwhile, the other process resulting from the \fIfork\fR, which is theparent process, \fIwait\|\fRs for the child process to die.When this happens, the Shell knows the command is finished, soit types its prompt and reads the typewriter to obtain anothercommand..pgGiven this framework, the implementation of background processesis trivial; whenever a command line contains ``&'',the Shell merely refrains from waiting for the processwhich it createdto execute the command..pgHappily, all of this mechanism meshes very nicely withthe notion of standard input and output files.When a process is created by the \fIfork\fR primitive, itinherits not only the core image of its parentbut also all the files currently open in its parent,including those with file descriptors 0 and 1.The Shell, of course, uses these files to read commandlines and to write its prompts and diagnostics, and in the ordinary caseits children_the command programs_inherit them automatically.When an argument with ``<'' or ``>'' is given however, theoffspring process, just before it performs \fIexecute,\fRmakes the standard I/Ofile descriptor 0 or 1 respectively refer to the named file.This is easybecause, by agreement,the smallest unused file descriptor is assignedwhen a new file is \fIopen\fR\|ed(or \fIcreate\fR\|d);it is only necessary to close file 0 (or 1)and open the named file.Because the process in which the command program runs simply terminateswhen it is through, the association between a filespecified after ``<'' or ``>'' and file descriptor 0 or 1 is endedautomatically when the process dies.Thereforethe Shell need not know the actual names of the fileswhich are its own standard input and output, since it neednever reopen them..pgFilters are straightforward extensionsof standard I/O redirection with pipes usedinstead of files..pgIn ordinary circumstances, the main loop of the Shell neverterminates.(The main loop includes thatbranch of the return from \fIfork\fR belonging to theparent process; that is, the branch which does a \fIwait\fR, thenreads another command line.)The one thing which causes the Shell to terminate isdiscovering an end-of-file condition on its input file.Thus, when the Shell is executed as a command witha given input file, as in.dcsh <comfile.ecthe commands in \fIcomfile\fR will be executed untilthe end of \fIcomfile\fR is reached; then the instance of the Shellinvoked by \fIsh\fR will terminate.Since this Shell processis the child of another instance of the Shell, the \fIwait\fRexecuted in the latter will return, and anothercommand may be processed..s26.6 Initialization.esThe instances of the Shell to which users typecommands are themselves children of another process.The last step in the initialization of \*sUNIX\*n is the creation ofa single process and the invocation (via \fIexecute\fR)of a program called \fIinit\fR.The role of \fIinit\fR is to create one processfor each typewriter channel which may be dialed up by a user.The various subinstances of \fIinit\fR open the appropriate typewritersfor input and output.Since when \fIinit\fR was invoked there wereno files open, in each process the typewriter keyboard willreceive file descriptor 0 and the printer file descriptor 1.Each process types out a message requesting that the user log inand waits, reading the typewriter, for a reply.At the outset, no one is logged in,so each process simply hangs.Finally someone types his name or other identification.The appropriate instance of \fIinit\fR wakes up, receives the log-inline, and reads a password file.If the user name is found, and ifhe is able to supply the correct password, \fIinit\fRchanges to the user's default current directory, setsthe process's user \*sID\*n to that of the person logging in, and performsan \fIexecute\fR of the Shell.At this point the Shell is ready to receive commandsand the logging-in protocol is complete..pgMeanwhile, the mainstream path of \fIinit\fR (the parent of allthe subinstances of itself which will later become Shells)does a \fIwait\fR.If one of the child processes terminates, eitherbecause a Shell found an end of file or because a usertyped an incorrect name or password, this path of \fIinit\fRsimply recreates the defunct process, which in turn reopens the appropriateinput and output files and types another login message.Thus a user may log out simply by typing the end-of-filesequence in place of a command to the Shell..s26.7 Other programs as Shell.esThe Shell as described above is designed to allow usersfull access to the facilities of the system, since it willinvoke the execution of any programwith appropriate protection mode.Sometimes, however, a different interface to the systemis desirable, and this feature is easily arranged..pgRecall that after a user has successfully logged in by supplyinghis name and password, \fIinit\fR ordinarily invokes the Shellto interpret command lines.The user's entryin the password file may contain the nameof a program to be invoked after login instead of the Shell.This program is free to interpret the user's messagesin any way it wishes..pgFor example, the password file entriesfor users of a secretarial editing systemspecify that theeditor \fIed\fR is to be used instead of the Shell.Thus when editing system users log in, they are inside the editor andcan begin work immediately; also, they can be prevented frominvoking \*sUNIX\*n programs not intended for their use.In practice, it has proved desirable to allow a temporaryescape from the editorto execute the formatting program and other utilities..pgSeveral of the games (e.g., chess, blackjack, 3D tic-tac-toe)available on \*sUNIX\*n illustratea much more severely restricted environment.For each of these an entry existsin the password file specifying that the appropriate game-playingprogram is to be invoked instead of the Shell.People who log in as a playerof one of the games find themselves limited to thegame and unable to investigate the presumably more interestingofferings of \*sUNIX\*n as a whole.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -