stdin 上的 close/fclose 是否保证正确?

发布于 2024-07-08 16:34:12 字数 147 浏览 8 评论 0原文

似乎以下调用执行了您所期望的操作(关闭流并不允许任何进一步的输入 - 等待流上的输入的任何操作都会返回错误),但它是否保证在所有编译器/平台上都是正确的?

close(fileno(stdin));
fclose(stdin);

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);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

雪花飘飘的天空 2024-07-15 16:34:12

fclose(stdin) 会导致进一步使用 stdin(隐式或显式)来调用未定义的行为,这是一件非常糟糕的事情。 它不会“禁止输入”。

close(fileno(stdin)) 导致在当前缓冲区耗尽后,从 stdin 输入的任何进一步尝试都会失败,并显示 EBADF,但只有在您打开另一个文件之前,该文件将成为 fd #0 并且会发生不好的事情

更稳健的方法可能是:

int fd = open("/dev/null", O_WRONLY);
dup2(fd, 0);
close(fd);

添加一些错误检查。 这将确保所有读取(在当前缓冲区耗尽后)都会导致错误。 如果您只是希望它们导致 EOF,而不是错误,请使用 O_RDONLY 而不是 O_WRONLY

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.

撩起发的微风 2024-07-15 16:34:12

不要关闭 fileno(FILE*)。 FILE 是一个缓冲对象。 研究其实现并干预其状态会带来所有其他软件模块上类似不当行为所带来的警告和危险。

不要这样做。

啊。 严重地。 可恶的。

DO NOT DO a close on fileno(FILE*). FILE is a buffering object. Looking into its implementation and meddling with its state carries all the caveats and dangers that would come with similar misbehavior on any other software module.

Don't do it.

AGH. Seriously. Nasty.

禾厶谷欠 2024-07-15 16:34:12

没有什么能保证在所有可能的操作系统上都是正确的。 但是,调用 fclose(stdin) 可以在任何 POSIX 兼容操作系统以及 Windows 操作系统上运行,因此您目前应该可以使用几乎所有常用的命令。

正如前面的答案和我的评论所述,不需要在文件句柄上调用 close 。 fclose() 将正确地为您关闭所有内容。

Nothing is guaranteed correct across every possible operating system. However, calling fclose(stdin) will work on any POSIX compliant operating system as well as Windows operating systems, so you should hit pretty much anything in general use at the moment.

As stated by the previous answer as well as my comment, there is no need to call close on the file handle. fclose() will properly close everything down for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文