编写一个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 }

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

猜你喜欢

转载自blog.csdn.net/xiaodu655/article/details/79750521
今日推荐