实现一个简单shell

用下图的时间轴来表示事件的发生次序。其中时间从左向右。shell由标识为bash的方块代表,它随着时间的流逝从左向右移动。shell从用户读入字符串”ls”。shell建立一个新的进程,然后在那个进程中运行ls程序并等待那个进程结束。然后shell读取新的一行输入,建立一个新的进程,在这个进程中运行程序并等待这个进程结束。
这里写图片描述
所以要写一个shell,需要循环以下过程:
1.获取命令行
2.解析命令行
3.建立一个子进程(fork)
4.替换子进程(execvp)
5.父进程等待子进程退出(wait)
代码实现:

1 #include <stdio.h>                                                                                          
  2 #include <unistd.h>
  3 #include <ctype.h>
  4 #include <stdlib.h>
  5 #include <sys/types.h>
  6 #include <sys/wait.h>
  7 
  8 char* argv[8];
  9 int argc = 0;
 10 void do_parse(char* buf){
 11     int i;
 12     int status = 0;
 13     for(argc=i=0;buf[i];i++){
 14         if(!isspace(buf[i]) && status == 0){
 15             argv[argc++] = buf + i;
 16             status = 1;
 17         }else if(isspace(buf[i])){
 18             status = 0;
 19             buf[i] = 0;
 20         }
 21     }
 22     argv[argc] = NULL;
 23 }
 24 
 25 void do_execute(void){
 26     pid_t pid = fork();
 27     switch(pid){
 28     case -1:
 29         perror("fork");
 30         exit(EXIT_FAILURE);
 31         break;
 32     case 0:
 33         execvp(argv[0],argv);
 34         perror("execvp");
 35         exit(EXIT_FAILURE);
 36     default:
 37         {
 38             int st;
 39             while(wait(&st) != pid)
 40                 ;
 41         }
 42     }
 43 }                                                                                                           
 44 
 45 int main(){
 46     char buf[1024] = {};
 47     while(1){
 48         printf("myshell# ");
 49         scanf("%[^\n]%*c",buf);
 50         do_parse(buf);
 51         do_execute();
 52     }
 53     return

运行结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/liru_1996/article/details/80186768
今日推荐