自主实现一个minishell程序

此时没有重定向功能
我们知道对于Linux,shell就是个命令行解释器,当我们输入相关的命令,会去执行相关的操作。

比如当我们输入ls -a -l命令,shell就会打印出当前目录的内容,这是如何实现的?shell自己就是一个进程,当我们输入ls之类的命令,它会通过fork,exec函数去创建一个新的子进程去执行相关操作。因此我们也可以利用这个来实现一个简单的shell。

当然,这个shell足够简单,并不能像Linux内置的shell那么强大支持各种操作,报错,等等。

#include <stdio.h>
  2 #include <unistd.h>
  3 #include <stdlib.h>
  4 #include <string.h>
  5 int main(){
  6 //1.等待用户输入
  7     while(1){ 
  8         printf("[fw@localhost$ root] ");
  9         char str[1024];//设置最大的长度
 10         if(scanf("%[^\n]%*c",str)!=1){
 11             getchar();
 12             continue;
 13         } 
 14     //2.解析输入数据,用数组存储起来,
 15         char* s[32]={0};
 16         char* start = str;
 17         char* end = str; 
 18         int i = 0;
 19         while(*end !='\0'){                                                 
 20                 if(*end!=' '){ 
 21                     s[i++] = end;
 22                 while(*end!=' '&&*end!='\0'){
 23                     end++;
 24                 }
 25             }
 26             *end = '\0';
             end++;
 28         }
 29         s[i]= NULL;
 30         if(strcmp(s[0],"cd") == 0){
 31             //   int chdir(const char *path);
 32             chdir(s[1]);
 33             continue;
 34         }
 35 //3.创建子进程,在子进程中进行数据读
 36 //4.等待子进程退出
 37         pid_t pid;
 38         pid = fork();
 39         if(pid<0){
 40             continue;
 41         }
 42         else if(pid == 0){//创建一个子进程执行逻辑
 43           //    int execvp(const char *file, char *const argv[]);
 44              if(execvp(s[0],s)<0){
 45                  perror("");
 46                  }
 47              exit(0);
 48         }
 49         wait(NULL);//父进程等待子进程的推出,防止产生僵尸进程
 50     }
 51     return 0;   
 52 }

猜你喜欢

转载自blog.csdn.net/boke_fengwei/article/details/89109267