此程序适用于smarthistory()的一个方面的例外。我无法弄清楚为什么当我从smarthistory数组输入一个命令号时为什么它不执行。输入命令从列表中执行后,甚至没有发生任何事情,甚至没有发生后的printf语句。我正在使用gcc编译器。
const int MAX_HISTORY=100;
const int MAX_COMMAND_LENGTH=64;
char history[100][64];
int historyCount = 0;
char smarthistory[100][64];
int smarthistoryCount=0;
void chopnl(char *s) { //strip '\n'
s[strcspn(s, "\n")] = '\0';
}
void printHistory() {
int i;
for (i = 0; i < historyCount; i++)
printf("%d | %s\n", i, history[i]);
}
void printSmartHistory() {
int i;
for (i = 0; i < smarthistoryCount; i++)
printf("%d | %s\n", i, smarthistory[i]);
}
void isPartialMatch(char *commandQuery,char *history, int historyString)
{
int lengthOfQuery=strlen(commandQuery);
if(strncmp( history, commandQuery,lengthOfQuery)==0)
{
memcpy(smarthistory[smarthistoryCount++], history, strlen(history) + 1);
}
else
return;
}
void smartHistory()
{
char commandQuery[MAX_COMMAND_LENGTH];
int commandNumber=0;
int i=0;
printHistory();
printf("enter partial command:> ");
fgets(commandQuery,MAX_COMMAND_LENGTH,stdin);
chopnl(commandQuery);
//printf("%d", strlen(commandQuery));
for(i=0;i<=historyCount;i++)
{
isPartialMatch(commandQuery, history[i], i);
}
printf("SmartHistory Search Results\n");
printSmartHistory();
printf("enter a command number to execute:> ");
scanf("%d", commandNumber);
//chopnl(commandNumber);
printf("command entered >");
handleCommand(smarthistory[commandNumber]);
}
void placeInHistory(char *command) {
// printf("command:> %s |stored in:> %d",command,historyCount );
memcpy(history[historyCount++], command, strlen(command) + 1);
}
int main(int argc, char** argv) {
char command[MAX_COMMAND_LENGTH];
while (1) {
printf("SHELL:>");
fgets(command, MAX_COMMAND_LENGTH, stdin);
chopnl(command);
if (strcmpi(command, "exit") == 0)
return EXIT_SUCCESS;
placeInHistory(command);
handleCommand(command);
}
return (EXIT_SUCCESS);
}
int handleCommand(char *command) {
pid_t pid;
int test=0;
pid = fork();
if (pid > 0) {
wait(&test);
} else if (pid == 0) {
execCommand(command);
exit(0);
} else {
printf("ERROR");
}
}
int execCommand(char *command) {
//system(command);
if (strcmpi(command, "history") == 0)
{
printHistory();
}
else if(strcmpi(command, "smarthistory") == 0)
{
smartHistory();
}
else if (strcmpi(command, "ls") == 0 || (strcmpi(command, "pwd") == 0)) {
char *path[] = {"/bin/", NULL};
strcat(path[0], command);
execve(path[0], path, NULL);
}else{system(command);}
}
答案 0 :(得分:1)
重新检查:
char *path[] = {"/bin/", NULL};
strcat(path[0], command);
path[0]
初始化为const char*
,您无法使用strcat()
。
另一个:
memcpy(smarthistory[smarthistoryCount++], history, strlen(history) + 1);
源和目的地不应该是同一类型,char*
?
另外,我建议使用char* history[MAX_HLEN]
char history[x][y]
。
答案 1 :(得分:0)
我不确定,但看起来“历史”和“智能历史”的处理应该从execCommand
移到handleCommand
并且应该发生在分叉状态。可能还有其他错误。
答案 2 :(得分:0)
问题解决了问题我需要添加'&amp;'在语句中的commandNumber之前:scanf(“%d”,commandNumber);位于smartHistory功能中。令我感到奇怪的是,我创建了另一个版本,我将“history”和“smarthistory”移动到handle命令函数而不是execCommand函数。当我这样做时程序打印shell提示3次...如果有人知道原因,请告诉我。但是在上面的版本中只添加'&amp;'效果很好。