c++ - 错误代码 : how to set and check errno

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

我试图了解在 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) 的初始代码将不起作用。

这是预期的行为吗?

最佳答案

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

关于c++ - 错误代码 : how to set and check errno,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52384571/

相关文章:

c++ - 这个 C++ 类声明是什么意思?

c++ - 无法使用自定义结构的属性

linux - 在不依赖任何共享库的 Linux 上构建可执行文件

java - 使用java代码从Linux机器访问共享文件夹

c++ - 简单的运算符重载不起作用

c++ - 定义模板化运算符重载时出错

c++ - 在指针中存储无符号整数

c++ - unordered_map 中迭代器的效率 (C++)

java - Ubuntu 12.04 - Eclipse 寻找不同的 libswt-gtk

c++ - 可以使用移动/交换 c++11 来延长返回的临时变量的生命周期吗