[Linux] - implement a command line interpreter under Linux

Keywords: shell Linux

Mini shell

When we first got to know Linux, because this is an operating system without a mouse, we executed ls, pwd, cd and other commands in the black box, which we talked about in the last lesson After process control We found that we can also make a simple command line interpreter.

Next, paste the source code directly, because what we have done is not very good, so we can run it and play it by ourselves. When the final version is finished, I will explain how to implement it step by step

  1 #include<iostream>                 
  2 #include<string>                   
  3 #include<cstdio>                   
  4 #include<cstring>                  
  5 #include<stdlib.h>                 
  6 #include<unistd.h>                 
  7 #include<sys/types.h>              
  8 #include<sys/wait.h>               
  9 using namespace std;                
 10                                     
 11 #define NUM 32                      
 12 int main()                          
 13 {                                   
 14     char* argv[NUM];                
 15     char buff[1024] = {0};          
 16     for(;;){                        
 17         string command;             
 18         string tips = "[xxx@localhost yyy]#"; 
 19         cout << tips;               
 20         fgets(buff,sizeof(buff)-1,stdin);
 21         buff[strlen(buff)-1] = 0;   
 22         argv[0] = strtok(buff," ");                                                
 23         int i = 0;                  
 24         while(argv[i] != NULL)      
 25         {                                                                          
 26             i++;
 27             argv[i] = strtok(NULL," ");
 28         }
 29         pid_t id = fork();
 30         if(id == 0){
 31             cout << "child running ..."<<endl;
 32             execvp(argv[0],argv); 
 33             exit(1);
 34         }
 35         else{
 36             int status = 0;
 37             waitpid(id,&status,0);
 38             cout << "exit code: "<<WEXITSTATUS(status)<<endl;
 39         }
 40     }    
 41     return 0;
 42 }        

Posted by Sobbs on Fri, 08 Nov 2019 08:11:00 -0800