当前位置:主页 > 查看内容

实现简单的shell

发布时间:2021-07-09 00:00| 位朋友查看

简介:实现一个minishell经验3 ↑ 实现简易shell shell shell的实现 shell 命令行解释器本质就是一个程序功能是将用户所要进行的操作传递给内核。 shell的实现 首先我们需要知道命令行开头的内容是啥。 为了区别系统的shell我将自己写的用户名改为“ljl1” # inclu……

实现一个minishell(经验+3 ↑)

实现简易shell


shell?

命令行解释器(本质就是一个程序),功能是将用户所要进行的操作传递给内核。在这里插入图片描述


shell的实现

首先我们需要知道命令行开头的内容是啥。
在这里插入图片描述
为了区别系统的shell,我将自己写的用户名改为“ljl1”;

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/wait.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
    while(1)
    {
        char buf[1024] = {0};
        printf("[ljl1@VM-0-5-centos Shell]$ ");
        fflush(stdout);//手动刷新缓冲区
        fgets(buf,1023,stdin);//从标准输入中读取1023个字节到buf中,留一个字节放\0
        buf[strlen(buf)-1] = '\0'; 
        char *str = buf;
        int redirect_flag = 0;//1-清空,2-追加重定向;
        char *redirect_file = NULL;
        while(*str != '\0')
        {
            if(*str == '>')
            {
                redirect_flag = 1;
                *str = '\0';
                str++;
                if(*str == '>')
                {
                    redirect_flag = 2;
                    str++;
                }
                while(*str != '\0' && *str == ' ')
                    str++;
                redirect_file = str;
                while(*str != '\0' && *str != ' ')
                    str++;
                *str = '\0';
             }
            str++;
        }

        char *ptr = buf;
        char myargv[32][32] = {{0}};
        int myargc = 0;
        while(*ptr != '\0')
        {
            if(!isspace(*ptr))
            {
                int count = 0;
                while(!isspace(*ptr) && *ptr != '\0')
                {
                    myargv[myargc][count] = *ptr;
                    count++;
                    ptr++;
                }
                myargc++;
            }
            ptr++;
        }
        char* arg[32] = {NULL};
        int i = 0;
        for(i = 0;i<myargc;++i)
        {
            arg[i] = myargv[i];
        }
        arg[myargc] = NULL;
        pid_t pid = fork();
        if(pid < 0)
            continue;
        else if(pid == 0)
        {
            if(redirect_flag == 1)
            {
                    int fd = open(redirect_file, O_CREAT|O_TRUNC|O_WRONLY,0664);
                    dup2(fd,1);
            }
             else if(redirect_flag == 2)
            {
                int fd = open(redirect_file,O_CREAT|O_APPEND|O_WRONLY,0664);
                dup2(fd,1);
            }
            execvp(arg[0],arg);
            exit(-1);
        }
        wait(NULL);
    }
    return 0;
}

走起~

在这里插入图片描述
完成。


;原文链接:https://blog.csdn.net/qq_43560037/article/details/115444943
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!
上一篇:点阵模块原理学习 下一篇:没有了

推荐图文

  • 周排行
  • 月排行
  • 总排行

随机推荐