Linux 模拟实现shell

Linux下利用程序替换来实现shell(exec*函数调用)

   1 #include <stdio.h>                                                                                       
   2 #include <unistd.h>
   3 #include <stdlib.h>
   4 #include <sys/wait.h>
   5 #include <string.h>
   6 
   7 #define NUM 128
   8 #define CMD_NUM 64
   9 
   10 int main()
   11 {
   12   char command[NUM];
   13     for( ; ; )
   14     {
   15       char *arvg[CMD_NUM]={NULL};
   16       //1.打印提示符
   17       command[0]='\0';//用折中方式,可以做到O(1)时间复杂度,清空字符串
   18       printf("[who@myhome mini_shell]#");
   19       fflush(stdout);
   20 
   21       //2.获取字符串
   22       fgets(command,NUM,stdin);
   23       command[strlen(command)-1]='\0';//将回车'\n'置为\0   "ls\n\0";
   24       //printf("echo:%s\n",command);
   25     
   26       
   27       //"ls -a -l \0";
   28       //3.解析命令字符串 ,char* arvg[];
   29       //strtok();
   30       const char *sep=" ";
   31       arvg[0]=strtok(command,sep);
   32       int i=1;
   33       while(arvg[i]=strtok(NULL,sep))
   34       {
   35         i++;
   36       }
   37 
   38 
   39       //for(int i=0;arvg[i];i++)
   40       //{
   41       //printf("arvg[%d]:%s\n",i,arvg[i]);
   42       //}
   43 
   44 
   45       //4.检验命令是否需要shell本身执行,内建命令
   46       if(strcmp(arvg[0],"cd")==0)
   47       {
   48         if(arvg[1]!=NULL)
   49           chdir(arvg[1]);
   50         continue;
   51       }
   52 
   53       //5.执行第三方命令
   54       if(fork()==0)
   55       {
   56         //child
   57         execvp(arvg[0],arvg);
   58         exit(1);
   59       }
   60       int status=0;
   61       waitpid(-1,&status,0);
   62       printf("exit code %d\n",(status>>8)&0xFF);
   63 
   64     }
   65 
   66   return 0;
   67 }          

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值