Ai
1 Star 0 Fork 0

G_D_BIT/Linux-Creat-Code

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
2.26 KB
一键复制 编辑 原始数据 按行查看 历史
G_D_BIT 提交于 2023-05-10 16:25 +08:00 . Shell的简易实现
#include<stdio.h>
#include<assert.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#define MAX 1024
#define ARGC 24
#define SEP " "
int split(char* command,char* argv[])
{
argv[0] = strtok(command,SEP);
if(argv[0] == NULL)
{
return -1;
}
int i = 1;
while((argv[i++] = strtok(NULL,SEP)));
return 0;
}
void DebugPrint(char* argv[])
{
int i = 0;
while(argv[i] != NULL)
{
printf("%s\n",argv[i++]);
}
}
void ShowEnv()
{
extern char** environ;
for(int i = 0; environ[i]; ++i)
{
printf("%d:%s",i,environ[i]);
}
}
int main()
{
char myenv[24][1024];
int env_index = 0;
int last_exit = 0;
while(1)
{
printf("[zrb@mychine currpath currpath]# ");
fflush(stdout);
char command[MAX] = {0};
char* argv[ARGC] = {0};
char* s = fgets(command,sizeof(command),stdin);
command[strlen(command)-1] = '\0';
assert(s);
(void)s;
split(command,argv);
//DebugPrint(argv);
if(strcmp(argv[0],"cd") == 0)
{
if(argv[1] != NULL) chdir(argv[1]);
continue;
}
else if(strcmp(argv[0],"env") == 0)
{
ShowEnv();
continue;
}
else if(strcmp(argv[0],"export") == 0)
{
if(argv[1] != NULL)
{
strcpy(myenv[env_index],argv[1]);
putenv(myenv[env_index++]);
}
continue;
}
else if(strcmp(argv[0],"echo") == 0)
{
const char* targe_env = NULL;
if(argv[1][0] == '$')
{
if(argv[1][1] == '?')
{
printf("%d\n",last_exit);
}
else
{
targe_env = getenv(argv[1]+1);
if(targe_env) printf("%s:%s",argv[1]+1,targe_env);
}
continue;
}
else
{
for(int i = 1; argv[i]; ++i)
{
printf("%s ",argv[i]);
}
continue;
}
}
else if(strcmp(argv[0],"ls") == 0)
{
int pos = 0;
while(argv[pos]) pos++;
argv[pos++] = (char*)"--color=auto";
argv[pos] = NULL;
}
pid_t id = fork();
assert(id >= 0);
(void)id;
if(id == 0)
{
execvp(argv[0],argv);
exit(1);
}
int status = 0;
pid_t ret = waitpid(id,&status,0);
if(ret > 0)
{
last_exit = WEXITSTATUS(status);
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/GD_BIT/linux-creat-code.git
git@gitee.com:GD_BIT/linux-creat-code.git
GD_BIT
linux-creat-code
Linux-Creat-Code
master

搜索帮助