结合进程替换的内容,我们可以自己实现一个简单的shell,shell是命令行解释器

#include<stdio.h>
#include<unistd.h>
#include<sys/wait.h>
#include<string.h>
#include<stdlib.h>
#define MAX_C 128
#define MAX_CMD 32
int main()
{
  char command[MAX_C] = "";
  for(;;)
  {

    command[0] = '\0'; //使我们的command用O(1)的时间复杂度来完成重置
    printf("[fengjunzi@VM-4-2-centos mydir]# ");
    fflush(stdout);  //刷新输出缓冲区
    fgets(command,MAX_C,stdin);
    command[strlen(command) - 1] = '\0';




    //解析字符串中的指令放入指针数组
    char* argv[MAX_CMD] = {NULL};
    const char* sep = " ";
    argv[0] = strtok(command,sep);
    int i = 1;
    while(argv[i] = strtok(NULL,sep))
    {
      ++i;
    }


    //需要shell 本身执行的命令 -- 内建命令
    if(strcmp("cd",argv[0]) == 0)
    {
      if(argv[1] != NULL)
      {
        chdir(argv[1]);
      }
      continue;
    }


    //进程替换
    if(fork() == 0)
    {
      //child
      execvp(argv[0],argv);
      exit(-1);
    }
    wait(NULL);
    //printf("%s\n",command);
  }
  return 0;
}
09-16 07:57