#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;
}