下面的代码应该作为 shell 工作。它具有上一个和下一个选项、类似历史的功能、退出和执行命令。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define BUFFER_SIZE 256
#define HISTORY_LENGTH 128
int executeCommand(char*cmd)
{
return(!strcmp(cmd,"e\n"));
}
int exitCommand(char*cmd)
{
return (!strcmp(cmd,"exit\n"));
}
int previousCommand(char*cmd)
{
return (!strcmp(cmd,"p\n"));
}
int nextCommand(char*cmd)
{
return (!strcmp(cmd,"n\n"));
}
void execute(char *line)
{
line[strlen(line)-1]='\0';
char **arguments;
char* temp;
int i=0;
arguments=(char**)malloc(sizeof(char)*10);
temp=strtok(line," ");
arguments[i]=malloc(strlen(temp)*sizeof(char));
if(arguments[i]!=NULL)
{
strcpy(arguments[i],temp);
i++;
}
else
{
printf("Out of memory");
}
while(temp!=NULL)
{
temp=strtok(NULL," ");
if(temp==NULL){
arguments[i]=NULL;
}
else{
arguments[i]=malloc(strlen(temp)*sizeof(char));
if(arguments[i]!=NULL)
{
strcpy(arguments[i],temp);
i++;
}
}
}
printf("%s ",arguments[0]);
printf("%s ",arguments[1]);
printf("%s ",arguments[2]);
execvp(arguments[0],arguments);
}
int main(int argc, char*argV[]) {
int i;
char *cmd=(char*)malloc(sizeof(char)*BUFFER_SIZE);
char **history=NULL;
int historylength=0;
int currentCommand=0;
history=(char**)malloc(sizeof(char)*BUFFER_SIZE);
do{
fgets(cmd,BUFFER_SIZE-1,stdin);
if(exitCommand(cmd))
break;
else
if(previousCommand(cmd))
{
if(currentCommand>0)
printf("%s",history[--currentCommand]);
else if(currentCommand==0)
{
currentCommand=historylength;
printf("%s",history[--currentCommand]);
}
}
else
if(nextCommand(cmd))
{
if(currentCommand<historylength)
printf("%s",history[currentCommand++]);
}
else
if(executeCommand(cmd))
{
execute(history[--currentCommand]);
}
else
{
history[historylength]=malloc(strlen(cmd)*sizeof(char));
if(history[historylength]!=NULL)
{
strcpy(history[historylength],cmd);
currentCommand=++historylength;
}
else
{
printf("Out of memory");
break;
}
}
} while(1);
free(cmd);
for(i=0;i<historylength;i++)
free(history[i]);
free(history);
return 0;
}
我想让这个函数为 cat 工作。我输入 e cat main.c 我希望它执行 cat 命令但它什么也没做,我在这里做错了什么?我不是这方面的专家,所以我感谢所有帮助。