简易shell

shell是指提供使用者使用界面的软件,它接收命令,然后调用相关的应用程序。

shell的运行原理:

       shell用fork建立新进程,用execv函数簇在新进程中运行用户指定的程序,最后shell用wait命令等待新进程结束。wait系统调用同时从内核取得退出状态或者信号序列以告知子进程是如何结束的。


所以要写一个shell,需要循环以下过程:

 1.获取命令行

 2.解析命令行

 3.建立一个子进程(fork)

 4.替换子进程(execvp)

 5.父进程等待子进程退出(wait)

下面是一个简易的shell:

#include<unistd.h>
#include<sys/wait.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

char* argv[8];
int argc;

void do_parse(char* buf)
{
 int i;
 int status = 0;

 for(argc = i = 0;buf[i] ;i++){
    if(!isspace(buf[i]) && status == 0){
        argv[argc++] == buf+i;
        status = 1;
     }else if(isspace(buf[i])){
        status = 0;
        buf[i] = 0;
     }
 }
 argv[argc] = NULL;
}

void do_execute(void)
{
  pid_t pid = fork();
  switch(pid){
    case -1:
       perror("fork");
       exit(EXIT_FAILURE);
       break;
    case 0:
       execvp(argv[0],argv);
       perror("execvp");
       exit(EXIT_FAILURE);
    default:
      {
       int st;
 while(wait(&st) != pid)
             ;
      }
  }
}

int main(void)
{
  char buf[1024] = {};
  while(1){
    printf("myshell-> ");
    scanf("%[^\n]%*c",buf);
    do_parse(buf);
    do_execute();
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_36229332/article/details/79655246