代码拉取完成,页面将自动刷新
#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);
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。