测试效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/fb3ea0b3f3d0cd16f95027165372d410.png)
设置内建命令
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4e718626fdd71c7daa640f15397c213a.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b54db9d04efd0b47a166d5d183b42181.png)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MAX 1024
#define ARGV 64
int split_command(char* command, char** argv)
{
assert(command);
assert(argv);
argv[0] = strtok(command, " ");
if(argv[0] == NULL) return -1;
int i = 1;
while((argv[i++] = strtok(NULL, " ")))
{ }
return 0;
}
void showenv()
{
extern char** environ;
int i = 0;
while(environ[i])
{
printf("%d:%s\n", i, environ[i]);
++i;
}
}
int main()
{
int last_exit = 0;
char myenv[32][256];
int myenv_index = 0;
while(1)
{
char command[MAX] = {0};
printf("[user@mymachine curpath]# ");
fflush(stdout);
char* s = fgets(command, sizeof(command), stdin);
assert(s);
(void)s;
command[strlen(command)-1] = '\0';
char *argv[ARGV] = {NULL};
int n = split_command(command, argv);
if(n != 0) continue;
if(strcmp(argv[0], "export") == 0)
{
if(argv[1] != NULL)
{
strcpy(myenv[myenv_index], argv[1]);
putenv(myenv[myenv_index++]);
}
continue;
}
if(strcmp(argv[0], "env") == 0)
{
showenv();
continue;
}
if(strcmp(argv[0], "echo") == 0)
{
const char *target_env = NULL;
if(*argv[1] == '$')
{
if(argv[1][1] == '?')
{
printf("%d\n", last_exit);
continue;
}
target_env = argv[1]+1;
}
printf("%s=%s\n", argv[1]+1, getenv(target_env));
continue;
}
if(strcmp(argv[0], "ls") == 0)
{
int index = 0;
while(argv[index]) index++;
argv[index++] = (char*)"--color=auto";
argv[index] = NULL;
}
if(strcmp(argv[0], "cd") == 0)
{
if(argv[1] != NULL) chdir(argv[1]);
continue;
}
pid_t id = fork();
assert(id >= 0);
(void)id;
if(id == 0)
{
execvp(argv[0], argv);
exit(0);
}
int status = 0;
pid_t ret = waitpid(id, &status, 0);
if(ret > 0)
{
last_exit = WEXITSTATUS(status);
}
}
return 0;
}