It seems as though the following calls do what you'd expect (close the stream and not allow any further input - anything waiting for input on the stream returns error), but is it guaranteed to be correct across all compilers/platforms?
close(fileno(stdin));
fclose(stdin);
It does not "inhibit input". close(fileno(stdin)) causes any further attempts at input from stdin , after the current buffer has been depleted, to fail with EBADF , but only until you open another file, in which case that file will become fd #0 and bad things will happen.
The simple, non-technical, answer is that Ctrl + D terminates the STDIN file and that Ctrl + C terminates the active application. Both are handled in the keyboard driver and apply to all programs reading from the keyboard. To see the difference start a command line shell and enter the wc command with no arguments.
The stdin is the short form of the “standard input”, in C programming the term “stdin” is used for the inputs which are taken from the keyboard either by the user or from a file. The “stdin” is also known as the pointer because the developers access the data from the users or files and can perform an action on them.
The stdin , stdout , and stderr global constant pointers are standard streams for input, output, and error output. By default, standard input is read from the keyboard, while standard output and standard error are printed to the screen. These pointers can be used as arguments to functions.
fclose(stdin)
causes any further use of stdin
(implicit or explicit) to invoke undefined behavior, which is a very bad thing. It does not "inhibit input".
close(fileno(stdin))
causes any further attempts at input from stdin
, after the current buffer has been depleted, to fail with EBADF
, but only until you open another file, in which case that file will become fd #0 and bad things will happen.
A more robust approach might be:
int fd = open("/dev/null", O_WRONLY);
dup2(fd, 0);
close(fd);
with a few added error checks. This will ensure that all reads (after the current buffer is depleted) result in errors. If you just want them to result in EOF, not an error, use O_RDONLY
instead of O_WRONLY
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With