Linux 如何设置errno值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11699596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set errno value?
提问by JAN
I have two calls to two different methods :
我有两次调用两种不同的方法:
void func1()
{
// do something
if (fail)
{
// then set errno to EEXIST
}
}
And the second method :
第二种方法:
void func2()
{
// do something
if (fail)
{
// then set errno to ENOENT
}
}
When I set the
errnoto some value , what does it do ? just error checking ?How can I set
errnoin the above methodsfunc1andfunc2toEEXISTandENOENT
当我将 设置
errno为某个值时,它有什么作用?只是错误检查?如何设置
errno在上面的方法func1,并func2以EEXIST和ENOENT
Thanks
谢谢
采纳答案by cnicutar
For all practical purposes, you can treat errnolike a global variable (although it's usually not). So include errno.hand just use it:
出于所有实际目的,您可以将其视为errno全局变量(尽管通常不是)。所以包括errno.h并使用它:
errno = ENOENT;
You should ask yourself if errnois the best error-reporting mechanism for your purposes. Can the functions be engineered to return the error code themselves ?
您应该问问自己是否errno是最适合您的错误报告机制。这些函数可以设计为自己返回错误代码吗?
回答by perreal
#include <errno.h>
void func1()
{
// do something
if (fail)
{
errno = ENOENT;
}
}
回答by coanor
IMO, the standard errnodesigned for system level. My experience is do not pollute them. If you want to simulate the C standard errnomechanism, you can do some definition like:
IMO,errno为系统级设计的标准。我的经验是不要污染它们。如果你想模拟 C 标准errno机制,你可以做一些定义,如:
/* your_errno.c */
__thread int g_your_error_code;
/* your_errno.h */
extern __thread int g_your_error_code
#define set_your_errno(err) (g_your_error_code = (err))
#define your_errno (g_your_error_code)
and also you can still implement your_perror(err_code). More information, please refer to glibc's implementation.
而且您仍然可以实施your_perror(err_code). 更多信息请参考glibc的实现。

