该程序在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);}
}
最佳答案
重新检查:
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]
。关于c - Shell程序中的功能出现问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3910951/