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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 13:57:06  来源:igfitidea点击:

How to set errno value?

clinuxerror-handlingerrno

提问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

  }

}
  1. When I set the errnoto some value , what does it do ? just error checking ?

  2. How can I set errnoin the above methods func1and func2to EEXISTand ENOENT

  1. 当我将 设置errno为某个值时,它有什么作用?只是错误检查?

  2. 如何设置errno在上面的方法func1,并func2EEXISTENOENT

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的实现。