Проблема: В настоящее время, когда я набираю ls и нажимаю Ctrl+D, fgets считывает ввод, оболочка выполняет ls команда, перепечатывает приглашение и ожидает новых входных данных. Мне нужно нажать Ctrl+D второй раз (на пустой строке), чтобы оболочка действительно завершила работу.
Я попробовал проверить feof(stdin) сразу после fgets, но кажется, что feof не возвращает true, когда fgets успешно считывает символы перед EOF.
Код: Выделить всё
#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;
}
Подробнее здесь: https://stackoverflow.com/questions/798 ... ontains-te
Мобильная версия