В настоящее время я делаю свою собственную программу оболочки. Мне нужно сохранить историю последних 10 команд, которые пользователь вводит. Всякий раз, когда пользователь вводит команду, которая НЕ является обычной командой (например, история, привет, fakecommand и т. Д.), Она помещается в историю. Но всякий раз, когда пользователь вводит настоящую команду (пример ls, ps, top, cat и т. Д.), Он не добавляется в историю.Почему этот код не выполняется?
Я думаю, что это может иметь какое-то отношение к команде execvp, так как я считаю, что эта команда создает вилку и заставляет ребенка выполнить команду. Но я не уверен, что он должен это сделать, поскольку я добавляю команду в историю, прежде чем я даже выполню execvp.
//A method which increments the histIndex
int incrementIndex(int index) {
if (index != 9)
return index+1;
else
return 0;
}
//A method which adds the current command to history
void updateHistory(char *history[], char command[], int histIndex) {
history[histIndex] = realloc(history[histIndex], MAX_LENGTH); //Allocating space
strcpy(history[histIndex], command); //Put the current command in history
}
int main(int argc, char *argv[]) {
//while true, do
while (1) {
int pid = fork(); //fork, or start the first process
if (pid != 0) { //if pid is not 0, then this is the parent,
wait(NULL);
}
else { //Otherwise, we have the child
printf("%s> ", getenv("USER")); //print out the user's name + >
fgets(input, MAX, stdin); //Get the users input
strtok(input, "\n"); //Take the entire line and set it to input
updateHistory(history, input, histIndex); //Updating history
histIndex = incrementIndex(histIndex);
if (strcmp(input, "exit")==0) { //If the input is exit, then exit
exit(0);
}
//Else if the current command is history, then print the last 10 commands
else if (strcmp(input, "history")==0) {
getHistory(history, histIndex);
}
//Otherwise, do
else {
numTokens = make_tokenlist(input, tokens);
tokens[numTokens] = NULL;
char cmd[MAX_LENGTH];
strcpy(cmd, tokens[0]);
execvp(cmd, tokens);
printf("Error: %s not found.\n", cmd);
}
}
}
}
Функция '' '' '' '' '' '' '' '' 'приведет к утечке памяти, поскольку она не передает никакого существующего указателя выделения памяти в' history [] '' 'free()' перед тем, как сделать новое распределение. – user3629249
отправьте функцию 'incrementHistory()' – user3629249
после этой строки: 'printf (« Ошибка:% s не найден. \ N », cmd)' вставьте строку: 'exit (EXIT_FAILURE);', поскольку вы не хотите, чтобы ребенок должен действовать как родитель. – user3629249