This is the first programming job of the operating system principle course, which complements the functionality of the shell.
The main implementation of the basic three types of commands
- Executable program Commands
- REDIRECT Command
- Pipeline command
The implementation of the "base class" (Forgive me for using this word) is a struct cmd this struct is a member that is used to record the type of command.
Three classes, "means executable program ' | ' represents the pipeline command, ' < ' and ' > ' represent the redirection type.
Each type inherits the base class, and derives the corresponding three classes of struct
struct EXECCMD
struct REDIRCMD
struct PIPECMD
void Runcmd (struct cmd * cmd);
This function is the core of the real driver invocation implementation shell. is responsible for invoking the system interface function EXECV (), open (), close (), DUP (), pipe () and so on a series of functions to accomplish our established goal.
The job is to complete this function.
This is a recursive function!
Here's the code from GitHub that extracts only the Runcmd function
1 void2Runcmd (structCMD *cmd)3 {4 intp[2];//used for pipe line in shell5 intR//return value6 structExecCmd *Ecmd;7 structPipecmd *Pcmd;8 structRedircmd *Rcmd;9 Ten if(cmd = =0) OneExit0); A - Switch(cmd->type) { - default: thefprintf (stderr,"Unknown runcmd\n"); -Exit (-1); - - Case ' ': +Ecmd = (structexeccmd*) cmd; - if(ecmd->argv[0] ==0) +Exit0); A //fprintf (stderr, "exec not implemented\n"); at //Your code here ... - if(Access (ecmd->argv[0], S_IXUSR | S_IRUSR) = =0) - { -EXECV (ecmd->argv[0], ecmd->argv); - } - Else in { - if(ChDir ("/bin/") <0) to { +printf"Change directory failed on line%d\n", __line__); -Exit0); the } *EXECV (ecmd->argv[0], ecmd->argv); $ }Panax Notoginsengfprintf (stderr,"Execv ()%s failed in line%d\n", ecmd->argv[0], __line__); - Break; the + Case '>': A Case '<': theRcmd = (structredircmd*) cmd; + //fprintf (stderr, "redir not implemented\n"); - //Your code here ... $Close (rcmd->FD); $ if(Open (Rcmd->file, Rcmd->mode) <0) - { -fprintf (stderr,"Try to open:%s failed\n", rcmd->file); theExit0); - }WuyiRuncmd (rcmd->cmd); the Break; - Wu Case '|': -Pcmd = (structpipecmd*) cmd; About //fprintf (stderr, "Pipe not implemented\n"); $ //Your code here ... - if(Pipe (P) <0) - { -fprintf (stderr,"Call Syscall pipe () failed on line%d\n", __line__); AExit0); + } the - if(Fork1 () = =0) $ { theClose1); theDUP (p[1]); theClose (p[0]); theClose (p[1]); -Runcmd (pcmd->Left ); in } the the if(Fork1 () = =0) About { theClose0); theDUP (p[0]); theClose (p[0]); +Close (p[1]); -Runcmd (pcmd->Right ); the }Bayi theClose (p[0]); theClose (p[1]); - wait (); - wait (); the Break; the } the theExit0); -}
Interested can click to view details
XV6-----Shell