Das Problem: Wenn ich derzeit ls eingebe und Strg+D drücke, liest fgets die Eingabe, die Shell führt das ls aus Befehl, gibt die Eingabeaufforderung erneut aus und wartet auf neue Eingaben. Ich muss Strg+D ein zweites Mal (in einer leeren Zeile) drücken, damit die Shell tatsächlich beendet wird.
Ich habe versucht, feof(stdin) unmittelbar nach fgets zu überprüfen, aber es scheint, dass feof nicht true zurückgibt, wenn fgets erfolgreich Zeichen vor dem EOF liest.
Code: Select all
#include "kell.h" // Includes standard headers like stdio.h, stdlib.h, string.h, unistd.h, sys/wait.h
void* resize(void* ptr, size_t new_size) {
void* temp_ptr = realloc(ptr, new_size);
if (temp_ptr == NULL) {
perror("kell: realloc");
return NULL;
}
return temp_ptr;
}
int main(int argc, char** argv) {
size_t buff_capacity = 48 * sizeof(char);
char* buff = malloc(buff_capacity);
while (1) {
printf("kell$ ");
// I attempt to read input here
fgets(buff, buff_capacity, stdin);
// I expect this to catch Ctrl+D even if I wrote text, but it doesn't
if (feof(stdin) != 0) {
printf("\n");
exit(EXIT_SUCCESS);
}
// Logic to handle resizing if buffer is full...
while((buff[strlen(buff) - 1] != '\n')) {
int current_length = strlen(buff);
char* tmp = resize(buff, buff_capacity * 2);
if (tmp != NULL) {
buff = tmp;
buff_capacity *= 2;
} else {
printf("not enough memory");
continue;
}
fgets(buff + current_length , buff_capacity - current_length, stdin);
if (feof(stdin) != 0) {
printf("\n");
exit(EXIT_SUCCESS);
}
}
// Tokenization and Execution Logic...
buff[strlen(buff) - 1] = '\0';
char* argsToSendExec[MAX_ARGC];
int a = 0;
char* token = strtok(buff, " ");
while (token != NULL) {
argsToSendExec[a++] = token;
token = strtok(NULL, " ");
}
argsToSendExec[a] = NULL;
pid_t cpid = fork();
if (cpid < 0) {
perror("fork");
return EXIT_FAILURE;
}
if (cpid == 0) {
if (execvp(argsToSendExec[0], argsToSendExec) == -1) {
perror("execvp");
return EXIT_FAILURE;
}
}
wait(NULL);
}
return EXIT_SUCCESS;
}
Mobile version