he xv6 shell uses the above calls to run programs on behalf of users. The main structure ofthe shell is simple; see main (user/sh.c:145). The main loop reads a line of input from the user withgetcmd. Then it calls fork, which creates a copy of the shell process. The parent calls wait,while the child runs the command. For example, if the user had typed “echo hello” to the shell,runcmd would have been called with “echo hello” as the argument. runcmd (user/sh.c:58) runsthe actual command. For “echo hello”, it would call exec (user/sh.c:78). If exec succeeds thenthe child will execute instructions from echo instead of runcmd. At some point echo will callexit, which will cause the parent to return from wait in main (user/sh.c:145).
在xv6 shell中,当用户输入一个命令时,shell会创建一个子进程来执行该命令,而父进程则负责等待子进程的完成。具体的流程如下:
-
Shell程序通过调用fork函数(user/sh.c:58)创建一个子进程。这个子进程是父进程的副本,包括程序、数据和文件描述符等信息。
-
在子进程中,shell解析用户输入的命令,确定要执行的操作。这一部分逻辑由runcmd函数(user/sh.c:58)处理。根据命令的类型,runcmd可能会调用不同的函数来执行相应的操作,例如执行可执行程序的exec函数、建立管道通信的pipe函数等。
-
如果命令是一个可执行程序,那么shell会调用exec函数(user/sh.c:78)来执行该程序。这样,子进程将执行新的程序代码,取代掉原来的shell代码。
-
在某个时刻,子进程执行的程序完成了它的任务,可能会调用exit函数来终止自己的执行。这会导致父进程从wait函数(user/sh.c:145)中返回,继续执行其他操作。