error_code:如何设置和检查errno

问题描述 投票:4回答:1

当我调用在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)的初始代码不起作用。

这是预期的行为吗?

c++ linux c++11 error-code
1个回答
4
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.