my_shell

时间:2021-07-21 09:30:11
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<pwd.h>
#include<limits.h>
#include<bits/local_lim.h>

int main(int argc, const char *argv[])
{
    while(1){
        int i=0,j=0,p=0;
        char buf[100]={0};              //存储命令
        char host[HOST_NAME_MAX]={0};   //存储主机名
        gethostname(host,sizeof(host));
        uid_t uid=getuid();             //uid
        char pwd[PATH_MAX]={0};         //用于存储当前路径
        getcwd(pwd,sizeof(pwd));
        printf("%s@%s %s%c ",getpwuid(uid)->pw_name,host,pwd,getuid()?'$':'#');fflush(stdout);
        gets(buf);
        char* ag[5]={0};
        for(i=0;i<5;i++){
            ag[i]=(char* )malloc(sizeof(10));
        }
        //将命令分解为字符串数组
        i=0;
        while(1){
            if(' '==buf[i]){
                strncpy(ag[j],buf+p,i-p);
                p=i+1;
                j++;
            }

            if('\0'==buf[i]){
                strncpy(ag[j],buf+p,i-p);
                ag[j+1]=NULL;   //exevp()需要
                break;
            }
            i++;
        }

        //处理cd
        if(!strcmp("cd",ag[0])){
            if(!strcmp("~",ag[1])){
                char tmp[20]="/home/";//,usr);
                ag[1]=strcat(tmp,getpwuid(uid)->pw_name);
            }

            char newPath[100]={0};
            strcpy(newPath,ag[1]);
            chdir(newPath);
            continue;
        }
        //处理ls *
        if(!strcmp(ag[0],"ls") && NULL!=ag[1] && !strcmp(ag[1],"*")){
            strcpy(ag[1],".");
            ag[2]=NULL;
        }

        pid_t pid=fork();
        if(0==pid){
            //重定向
            if(NULL!=ag[2] && !strcmp(ag[2],">")){
                FILE* fp1=freopen(ag[3],"w+",stdout);
            }
            if(NULL!=ag[2] && !strcmp(ag[2],">>")){
                FILE* fp2=freopen(ag[3],"a+",stdout);
            }
            if(NULL!=ag[2] && !strcmp(ag[2],"2>")){
                FILE* fp3=freopen(ag[3],"w+",stderr);
            }
            if(NULL!=ag[2] && !strcmp(ag[2],"<")){
                FILE* fp4=freopen(ag[3],"w+",stdin);
            }
            execvp(ag[0],ag);
        }
        else{
            wait(NULL);
        }
    }
    return 0;
}

执行结果

$./a.out
linux@ubuntu /home/linux/Desktop/161028$ ls
1  2  a.out  my_shell.c
linux@ubuntu /home/linux/Desktop/161028$ ls -l
total 24
-rw-rw-r-- 1 linux linux 2008 10月 28 21:15 1
-rw-rw-r-- 1 linux linux 4312 10月 28 21:18 2
-rwxrwxr-x 1 linux linux 7837 10月 29 12:48 a.out
-rw-rw-r-- 1 linux linux 1892 10月 29 12:48 my_shell.c
linux@ubuntu /home/linux/Desktop/161028$ cd ..
linux@ubuntu /home/linux/Desktop$ ls -l > 1
ls: cannot access >: No such file or directory
linux@ubuntu /home/linux/Desktop$ cat 1
-rw-rw-r-- 1 linux linux 0 10月 29 12:52 1
linux@ubuntu /home/linux/Desktop/hqyj$   

相关文章