我目前正在查看Linux内核(热管理)中的一些代码。在某些地方,有一个用于指示错误的返回值,该值在函数开始时设置为0。然后,在调用可能失败的函数时,使用|=
代替将其设置为新值=
。这是一个例子:
int ti_bandgap_read_temperature(struct ti_bandgap *bgp, int id,
int *temperature)
{
u32 temp;
int ret;
ret = ti_bandgap_validate(bgp, id);
if (ret)
return ret;
spin_lock(&bgp->lock);
temp = ti_bandgap_read_temp(bgp, id);
spin_unlock(&bgp->lock);
ret |= ti_bandgap_adc_to_mcelsius(bgp, temp, &temp);
if (ret)
return -EIO;
*temperature = temp;
return 0;
}
的定义ti_bandgap_validate
是:
/**
* ti_bandgap_validate() - helper to check the sanity of a struct ti_bandgap
* @bgp: struct ti_bandgap pointer
* @id: bandgap sensor id
*
* Checks if the bandgap pointer is valid and if the sensor id is also
* applicable.
*
* Return: 0 if no errors, -EINVAL for invalid @bgp pointer or -ERANGE if
* @id cannot index @bgp sensors.
*/
static inline int ti_bandgap_validate(struct ti_bandgap *bgp, int id)
因此,如果我的推理是正确的,则在调用时ti_bandgap_adc_to_mcelsius()
,的值ret
必须为0
(否则该函数将已经退出)。那么,为什么在|=
这里使用而不是=
?用全零的模式执行“或”操作只会返回正常模式。这是针对通常情况的某种优化,即该函数没有返回任何失败(即return value 0
)吗?还是我缺少其他区别?该代码在ARM体系结构上运行,因此可能必须对该平台进行特定的优化。
在这种情况下,没有理由使用,|=
但是,如果您要跟踪许多可能出错的函数,并在它们出错时作为返回码返回,则模式为
boolean error = false
error |= doFirstStep(...);
error |= doSecondStep(...);
error |= doThirdStep(...);
if (error) {
printf("error occurred: %s\n", strerror(errno));
}
它是C语言中较少使用的模式,偶尔在与C语言有某种相似性的语言中使用。在C语言中,大量的C库函数在成功操作后都会返回“错误代码”,该错误代码通常为0。
使用此模式时,用户将返回零作为成功条件。这意味着上面提到的log_and_recover()
可能将错误消息从error.ha静态变量中拉出,这是C#include <error.h>
例程常见的。
----继续说明为什么它经常在int字段上使用----
您还会看到带有int
错误的模式。
int error = 0; // or a variable that's defined to zero
error |= doFirstStep(...);
error |= doSecondStep(...);
error |= doThirdStep(...);
if (error != 0) {
... some error handling ...
}
当您看到此内容时,它与上面的想法相同,但是开发人员组合了两种模式。经常用于打包配置参数的位字段模式用于打包多种错误。通常,发生这种情况时,您会找到类似于以下内容的错误列表
#define ERROR_NO_DISK (1<<1);
#define ERROR_NO_NETWORK (1<<2);
#define ERROR_NO_SANITY (1<<3);
对于大多数项目来说,返回多个错误并将它们作为一个错误处理是非常不明智的。但是有时在错误抑制很重要的情况下才这样做。例如,如果您无法将消息从客户端传输到主机,则可能会抑制各种“打开套接字失败”,“无法写入套接字”,“无法复制到缓冲区”等。变成通用的“发送X失败”。一方面,整个顶层工作流程都失败了,如果需要,为什么仍然可以找到原因的详细信息。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句