Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is close/fclose on stdin guaranteed to be correct?

Tags:

c

stdio

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);
like image 939
Greg Rogers Avatar asked Nov 13 '08 20:11

Greg Rogers


People also ask

What happens if you close 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.

How do I close a stdin bash?

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.

Can stdin read files?

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.

Which is correct file pointer for standard input?

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.


1 Answers

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.

like image 189
R.. GitHub STOP HELPING ICE Avatar answered Sep 23 '22 23:09

R.. GitHub STOP HELPING ICE