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

📄 p4

📁 unix v7是最后一个广泛发布的研究型UNIX版本
💻
字号:
.SHVI. THE SHELL.PPFor most users,communication withthe systemis carried on with theaid of a program called the \&shell.The \&shell is acommand-line interpreter: it reads lines typed by the user andinterprets them as requests to executeother programs.(The \&shell is described fully elsewhere,.[bourne shell bstj%Q This issue.]so this section will discuss only the theory of its operation.)In simplest form, a command line consists of the commandname followed by arguments to the command, all separatedby spaces:.P1command arg\*s\d1\u\*n arg\*s\d2\u\*n .\|.\|. arg\*s\dn\u\*n.P2The \&shell splits up the command name and the arguments intoseparate strings.Then a file with name.UL commandis sought;.UL commandmay be a path name including the ``/'' character tospecify any file in the system.If.UL commandis found, it is brought intomemory 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..PPIf file.UL commandcannot be found,the \&shell generally prefixes a string such as.UL /\|bin\|/to.UL commandandattempts again to find the file.Directory.UL /\|bincontains commandsintended to be generally used.(The sequence of directories to be searchedmay be changed by user request.).SH6.1 Standard I/O.PPThe discussion of I/O in Section III 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 withthree open files with file descriptors0, 1, and 2.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 terminal.Thus programs that wish to write informativeinformation ordinarily use file descriptor 1.Conversely, file 0 starts off open for reading, and programs thatwish to read messages typed by the userread this file..PPThe \&shell is able to change the standard assignments ofthese file descriptors from theuser's terminal 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:.P1ls.P2ordinarily lists, on the typewriter, the names of the files in the currentdirectory.The command:.P1ls >there.P2creates a file called.UL thereand places the listing there.Thus the argument.UL >theremeans``place output on.UL there .''On the other hand:.P1ed.P2ordinarily enters the editor, which takes requests from theuser via his keyboard.The command.P1ed <script.P2interprets.UL scriptas a file of editor commands;thus.UL <scriptmeans ``take input from.UL script .''.PPAlthough 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..PPFile descriptor 2 is, like file 1,ordinarily associated with the terminal output stream.When an output-diversion request with ``>'' is specified,file 2 remains attached to the terminal, so that commandsmay produce diagnostic messages thatdo not silently end up in the output file..SH6.2 Filters.PPAn 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:.P1ls | pr \(mi2 | opr.P2.UL lslists the names of the files in the current directory;its output is passed to.UL pr ,whichpaginates its input with dated headings.(The argument ``\(mi2'' requestsdouble-column output.)Likewise, the output from.UL pris input to.UL opr ;this command spools its input onto a file for off-lineprinting..PPThis procedure could have been carried outmore clumsily by:.P1ls >temp1pr \(mi2 <temp1 >temp2opr <temp2.P2followed 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.UL 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.UL lsto provide such a wide variety of output options..PPA programsuch as.UL prwhich copies its standard input to its standard output(with processing)is called a.IT filter .Some filters that we have found usefulperformcharacter transliteration,selection of lines according to a pattern,sorting of the input,and encryption and decryption..SH6.3 Command separators; multitasking.PPAnother feature provided by the \&shell is relatively straightforward.Commands need not be on different lines; instead they may be separatedby semicolons:.P1ls; ed.P2will first list the contents of the current directory, then enterthe editor..PPA related feature is more interesting.If a command is followedby ``\f3&\f1,'' the \&shell will not wait for the command to finish beforeprompting again; instead, it is ready immediatelyto accept a new command.For example:.bd 3.P1as source >output &.P2causes.UL sourceto be assembled, with diagnosticoutput going to.UL output ;no matter how long theassembly takes, the \&shell returns immediately.When the \&shell does not wait forthe completion of a command,the identification number of theprocess running that command is printed.This identification may be used towait for the completion of the command or toterminate it.The ``\f3&\f1'' may be usedseveral times in a line:.P1as source >output & ls >files &.P2does both the assembly and the listing in the background.In these examples, an output fileother than the terminal was provided; if this had not beendone, the outputs of the various commands would have beenintermingled..PPThe \&shell also allows parentheses in the above operations.For example:.P1(\|date; ls\|) >x &.P2writes the current date and time followed bya list of the current directory onto the file.UL x .The \&shell also returns immediately for another request..SH 16.4 The \&shell as a command; command files.PPThe \&shell is itself a command, and may be called recursively.Suppose file.UL tryoutcontains the lines:.P1as sourcemv a.out testprogtestprog.P2The.UL mvcommand causes the file.UL a.outto be renamed.UL testprog..UL \&a.outis the (binary) output of the assembler, ready to be executed.Thus if the three lines above were typed on the keyboard,.UL sourcewould be assembled, the resulting program renamed.UL testprog ,and.UL testprogexecuted.When the lines are in.UL tryout ,the command:.P1sh <tryout.P2would cause the \&shell.UL shto execute the commandssequentially..PPThe \&shell has further capabilities, including theability to substitute parametersandto construct argument lists from a specifiedsubset of the file names in a directory.It also provides general conditional and looping constructions..SH 16.5 Implementation of the \&shell.PPThe 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 thenewline character ending the lineis typed, the \&shell's.UL readcall returns.The \&shell analyzes the command line, putting thearguments in a form appropriate for.UL execute .Then.UL forkis called.The child process, whose codeof course is still that of the \&shell, attemptsto perform an.UL executewith 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.UL fork ,which is theparent process,.UL wait sfor the child process to die.When this happens, the \&shell knows the command is finished, soit types its prompt and reads the keyboard to obtain anothercommand..PPGiven this framework, the implementation of background processesis trivial; whenever a command line contains ``\f3&\f1,''the \&shell merely refrains from waiting for the processthat it createdto execute the command..PPHappily, all of this mechanism meshes very nicely withthe notion of standard input and output files.When a process is created by the.UL forkprimitive, itinherits not only the memory image of its parentbut also all the files currently open in its parent,including those with file descriptors 0, 1, and 2.The \&shell, of course, uses these files to read commandlines and to write its prompts and diagnostics, and in the ordinary caseits children\(emthe command programs\(eminherit them automatically.When an argument with ``<'' or ``>'' is given, however, theoffspring process, just before it performs.UL execute,makes 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.UL open ed(or.UL create 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 filesthat are its own standard input and output, because it neednever reopen them..PPFilters are straightforward extensionsof standard I/O redirection with pipes usedinstead of files..PPIn ordinary circumstances, the main loop of the \&shell neverterminates.(The main loop includes thebranch of the return from.UL forkbelonging to theparent process; that is, the branch that does a.UL wait ,thenreads another command line.)The one thing that 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:.P1sh <comfile.P2the commands in.UL comfilewill be executed untilthe end of.UL comfileis reached; then the instance of the \&shellinvoked by.UL shwill terminate.Because this \&shell processis the child of another instance of the \&shell, the.UL waitexecuted in the latter will return, and anothercommand may then be processed..SH6.6 Initialization.PPThe instances of the \&shell to which users typecommands are themselves children of another process.The last step in the initialization ofthe systemis the creation ofa single process and the invocation (via.UL execute )of a program called.UL init .The role of.UL initis to create one processfor each terminal channel.The various subinstances of.UL initopen the appropriate terminalsfor input and outputon files 0, 1, and 2,waiting, if necessary, for carrier to be established on dial-up lines.Then a message is typed out requesting that the user log in.When the user types a name or other identification,the appropriate instance of.UL initwakes up, receives the log-inline, and reads a password file.If the user's name is found, and ifhe is able to supply the correct password,.UL initchanges to the user's default current directory, setsthe process's user \*sID\*n to that of the person logging in, and performsan.UL executeof the \&shell.At this point, the \&shell is ready to receive commandsand the logging-in protocol is complete..PPMeanwhile, the mainstream path of.UL init(the parent of allthe subinstances of itself that will later become \&shells)does a.UL wait .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.UL initsimply recreates the defunct process, which in turn reopens the appropriateinput and output files and types another log-in message.Thus a user may log out simply by typing the end-of-filesequence to the \&shell..SH6.7 Other programs as \&shell.PPThe \&shell as described above is designed to allow usersfull access to the facilities of the system, because 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 for..PPRecall that after a user has successfully logged in by supplyinga name and password,.UL initordinarily invokes the \&shellto interpret command lines.The user's entryin the password file may contain the nameof a program to be invoked after log-in instead of the \&shell.This program is free to interpret the user's messagesin any way it wishes..PPFor example, the password file entriesfor users of a secretarial editing systemmightspecify that theeditor.UL edis to be used instead of the \&shell.Thus when users of the editing system log in, they are inside the editor andcan begin work immediately; also, they can be prevented frominvokingprograms 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..PPSeveral of the games (e.g., chess, blackjack, 3D tic-tac-toe)available onthe systemillustratea 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 these games find themselves limited to thegame and unable to investigate the (presumably more interesting)offerings ofthe.UXsystemas a whole.

⌨️ 快捷键说明

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