I'm currently making my own shell program. I have to keep a history of the last 10 commands the user inputs. Whenever the user enters a command that ISN'T a regular command (for example history, hi, fakecommand, etc.) it is placed in history. But whenever the user inputs a real command (example ls, ps, top, cat, etc.) it is not added to history.
I think it might have something to do with the execvp command, since I believe this command creates a fork and makes the child execute the command. But I'm not sure that it should do that since I put the command in history before I even execute 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);
}
}
}
}