I’m writing my own shell in C and I need to detect EOF (for when I run ./myshell < commands.txt)
commands.txt contains:
ls
pwd
These both run fine separately from within the program. But when I run it with the text file, I get an infinite loop.
In my while(1) loop for the shell, the first thing I do is this:
if (feof(stdin)) { my_exit(); }
my_exit is simply:
void my_exit() {
printf("End of file! Bye\n");
exit(0);
}
Doesn’t exit(0) end the program (and the loop)? Why am I getting
End of File! ByeEnd of File! ByeEnd of File! ByeEnd of File! ByeEnd of File! ByeEnd of File! Bye…. etc
I have also tried doing the fgets == NULL way. Same loop
The problem is that
feof()tells you if the LAST input operation ran into EOF. But you’re not checking this until the next iteration. So when you’re at EOF, you dofgets()and then try to use the empty result that it returned.What’s happening is that you
fork()a child process, and then callexecvp()with an empty command name. This is failing, so the child process returns to the beginning of the loop, and does the same thing. Meanwhile, the parent process callsmy_exit(). So each child process forks another child of its own, and then exits.