gpt4 book ai didi

c - 打印到 stderr 时检查 fprintf 时出错

转载 作者:太空狗 更新时间:2023-10-29 16:50:50 27 4
gpt4 key购买 nike

根据文档,fprintf 可能会失败,并会在失败时返回一个负数。显然,在许多情况下检查此值很有用。

不过,我通常使用 fprintf 将错误消息打印到 stderr。我的代码通常看起来像这样:

rc = foo();
if(rc) {
fprintf(stderr, "An error occured\n");
//Sometimes stuff will need to be cleaned up here
return 1;
}

在这些情况下,fprintf 是否仍有可能失败?如果是这样,是否可以采取任何措施以某种方式显示错误消息,或者是否有比 fprintf 更可靠的替代方法?

如果不是,这样使用fprintf是否需要检查?

最佳答案

C 标准说文件流stdinstdoutstderr 应该连接到某处,但它们没有指定连接到哪里, 当然。(C11 §7.21.3 Files ¶7 :

At program startup, three text streams are predefined and need not be opened explicitly -- standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output). As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.

用重定向的标准流运行程序是完全可行的:

some_program_of_yours >/dev/null 2>&1 </dev/null

您的写入会成功 - 但信息不会去任何地方。一种更残酷的运行程序的方式是:

some_program_of_yours >&- 2>&- </dev/null

这一次,它在没有为 stdoutstderr 打开文件流的情况下运行——这违反了标准。在示例中它仍然从 /dev/null 读取,这意味着它没有从 stdin 获取任何有用的数据输入。

许多程序不会检查标准 I/O channel 是否打开。许多程序都懒得去检查错误消息是否已成功写入。通过 Tim Post 设计一个合适的回退作为概述和 whitey04并不总是值得付出努力。如果您在抑制输出的情况下运行 ls 命令,它会简单地执行它可以执行的操作并以非零状态退出:

$ ls; echo $?
gls
0
$ ls >&- 2>&-; echo $?
2
$

(已测试 RHEL Linux。)确实不需要它做更多事情。另一方面,如果您的程序应该在后台运行并写入日志文件,它可能不会向 stderr 写入太多内容,除非它无法打开日志文件(或点日志文件中的错误)。

请注意,如果您求助于 syslog(3) (或 POSIX ),您无法知道您的调用是否“成功”; syslog 函数均不返回任何状态信息。你只需要假设他们是成功的。因此,这是您最后的选择。

关于c - 打印到 stderr 时检查 fprintf 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4846562/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com