编写一个shell

编写shell的过程:
1.从标准输入中读入一个字符串。
2.解析字符串
3.创建一个子进程的执行程序。
4.子进程程序替换。
5.父进程等待子进程退出。

  2 #include<stdlib.h>
  3 #include<unistd.h>
  4 #include<sys/wait.h>
  5 #include<string.h>
  6 char *argv[8];
  7 int argc=0;
  8 void do_parse(char*buf)
  9 {
 10         int i;
 11         int status=0;
 12         for(argc=i=0;buf[i];i++)
 13         {
 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;//最后一个设置为NULL
 23 }
 24 void do_execute(void)//后三步
 25 {
 26         pid_t pid=fork();
 27         switch(pid){
 28         case -1:perror("fork");exit(EXIT_FAILURE);break;
 29         case 0:execvp(argv[0],argv);perror("execvp");
 30                 exit(EXIT_FAILURE);
 31         default:
 32         {
 33                 int st;
 34                 while(wait(&st)!=pid)
 35                         ;
 36         }
 37         }
 3 int main()
 40 {
 41         char buf[1024]={};
 43         while(1){
 44         printf("myshell>");
 45         scanf("%[^\n]%*c",buf);
 46         do_parse(buf);
 47         do_execute();
 48         }
 49 //      printf("%s\n",argv[0]); 
 50 }

这里写图片描述
这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值