shell

#include"../header/header.h"
#define NUM 1024
#define SIZE 32
#define SEP " "
#define CLOSE "\033[0m"
#define BLOD "\033[1m"
#define BEGIN(x,y) "\033["#x";"#y"m"


char cmd_line[NUM];
char *g_argv[SIZE];
char g_myval[32];
char Work_DIR[256];
extern char** environ;

int main()
{
    char shellbuffer[256] = {0};
    while(1)
    {
       
        read_history("command_history.txt");
        char *t = readline(BEGIN(49,34)"~$ " CLOSE);
        add_history(t);
        write_history("command_history.txt");
        memset(cmd_line, '\0', sizeof cmd_line);
        fflush(stdout);
        strncpy(cmd_line,t,strlen(t)+1);
        free(t);

        cmd_line[strlen(cmd_line)] = '\0';
        size_t index = 1;
        g_argv[0] = strtok(cmd_line, SEP);
        //ls实现
        if(strcmp(g_argv[0], "ls") == 0)
        {
            g_argv[index++] = "--color=auto";
        }

        //ll实现
        if(strcmp(g_argv[0], "ll") == 0)
        {
            g_argv[0] = "ls";
            g_argv[index++] = "-l";
            g_argv[index++] = "--color=auto";
        }

        //exit实现
        if(strcmp(g_argv[0], "exit") == 0){
            exit(0);
        }
        while(g_argv[index++] = strtok(NULL, SEP));//如果还对原串操作,就传入NULL

        //export实现
        if(strcmp(g_argv[0], "export") == 0 && g_argv[1] != NULL)
        {
            strcpy(g_myval, g_argv[1]);
            int ret = putenv(g_myval);
            if(ret == 0) printf("export success\n");
            continue;
        }

        //cd实现
        if(strcmp(g_argv[0], "cd") == 0)
        {
            if(g_argv[1] != NULL)
            {
                chdir(g_argv[1]);
            }
            else{
                 printf("没有此目录");
            }
            continue;
        }
        
 
        pid_t id = fork();//创建子进程
        if(id < 0)
        {
            perror("fork");
            exit(1);
        }
        else if(id == 0)
        {
            //子进程
            execvp(g_argv[0], g_argv);
            printf("执行失败,shell退出");
            //子进程能够运行到这里说明替换失败
            exit(1);
        }
        else
        {
            //父进程
            int status = 0;
            pid_t res = waitpid(-1, &status, 0);//阻塞式等待
            if(res > 0)//等待成功
            {
                printf("Running code: %d \n", WEXITSTATUS(status));
            }
        }
    }
 
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值