I'm trying to simulate a command line shell. The user inputs a shell command they want to input, e.g. /bin/pwd
and the code is meant to execute it.
The buffer is set to read a fixed number of chars (let's say 20 for example).
In the case that the user inputs more than 20 chars, the excess characters need to be flushed before the shell loops again.
I've been trying to do this like so:
int garbageCollector;
while ((garbageCollector = getchar()) != '\n' && garbageCollector != EOF);
But the problem is getChar()
requires you to input a char first.
Is there a way to flush stdin that doesn't require user to input anything?
while (1) {
// Prompt user for input
ssize_t readIn = read(STDIN_FILENO, buffer, BUF_SIZE + 1);
if (readIn < 0) {
perror("read() failed");
return 2;
}
// Null-terminate and remove line return
buffer[readIn - 1] = '\0';
char program[strlen(buffer)];
strcpy(program, buffer);
printf("program is: %s\n", program);
// Flush stdin
int garbageCollector;
while ((garbageCollector = getchar()) != '\n' && garbageCollector != EOF);
// Create child process
child = fork();
if (child < 0) {
perror("fork() failed");
return 3;
}
// Start alarm that is triggered after timeout exceeded
// which then kills child process
signal(SIGALRM, killChild);
alarm(timeout);
if (child == 0) { // Child
char* av[] = { program, NULL };
execve(program, av, NULL);
} else { // Parent
wait(NULL);
alarm(0); // Reset alarm if program executed
}
memset(buffer, 0, BUF_SIZE); // Flush buffer
}