【问题标题】:error_code: how to set and check errnoerror_code:如何设置和检查errno
【发布时间】:2018-09-18 10:30:28
【问题描述】:

我试图了解在 Linux 上调用设置 errno 的 C 函数时应该使用什么类别。

我不确定所有可能的错误代码都是由 POSIX 定义的,所以我很想使用system_category

但我喜欢稍后在我的代码中处理通用条件,所以我想做这样的事情:

std::error_code ec;
some_func(some_path, ec);

if (ec) {
  if (ec == std::errc::file_exists) {
    // special handling
  }
  return ec;
}

要在some_func() 中设置错误代码,我希望这样进行:

ec.assign(EEXIST, std::system_category());

主要基于这个讨论:

std::error_code ec;
if(-1 == open(...))
  ec = std::error_code(errno, std::system_category());
// To test using portable code
if(ec == std::errc::no_such_file_or_directory)
   ...
// To convert into nearest portable error condition (lossy, may fail)
std::error_condition ec2(ec.default_error_condition())

-- https://stackoverflow.com/a/40063005/951426

但是,在 Linux 上,使用 GCC 6.1.1,我有:

  • std::error_code(EEXIST, std::system_category()) == std::errc::file_exists 返回false
  • std::error_code(EEXIST, std::generic_category()) == std::errc::file_exists 返回true

我期望 errno + system_category 与 std::errc 条件相当。

这意味着如果我不使用通用类别,我检查 if (ec == std::errc::file_exists) 的初始代码将不起作用。

这是预期的行为吗?

【问题讨论】:

  • 也许你可以简单地使用 std::make_error_code(EEXIST) ?
  • 无法编译:error: no matching function for call to ‘make_error_code(int)’.
  • 发件人:en.cppreference.com/w/cpp/error/errc。看来您应该使用 std::make_error_code(std::errc::file_exists);或类似的东西。
  • 我以 EEXIST 为例,但在实践中我从 errno 获取值。我做不到std::make_error_code(errno)。我想避免在所有 errno 值上编写 switch-case,因为我假设系统和通用类别已经这样做了。

标签: c++ linux c++11 error-code


【解决方案1】:

这是最近在最新的 GCC 6、7 和 8 点版本中修复的错误。如果您使用的是最新的点版本,它将按您的预期工作。见https://gcc.gnu.org/bugzilla/show_bug.cgi?id=60555

【讨论】:

  • 哇,谢谢!如果这是一个 GCC 错误,我实际上已经搜索过了,但我没有找到它。遗憾的是,我有点坚持使用稍旧的 GCC 版本,因此我必须同时使用 generic_category() 来解决这个问题。
猜你喜欢
  • 1970-01-01
  • 2018-04-01
  • 1970-01-01
  • 2012-07-26
  • 2018-02-11
  • 2012-12-06
  • 1970-01-01
  • 2015-03-14
  • 2013-11-22
相关资源
最近更新 更多