本文介绍了error_code:如何设置和检查errno的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当试图调用在Linux上设置errno的C函数时,我试图了解应该使用的类别.

I'm trying to understand what category I should use, when calling a C function that sets errno on Linux.

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

I'm not sure all the possible error codes are defined by POSIX, so I'm tempted to use the system_category.

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

But I like to handle generic condition in my code later on, so I would like to do things like that:

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

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

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

To set the error code in some_func(), I expected to proceed like this:

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,我有:

However, on Linux, with GCC 6.1.1, I have:

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

我期望errno + system_category与std::errc条件具有可比性.

I was expecting the errno + system_category to be comparable with std::errc conditions.

这意味着如果我不使用通用类别,则检查if (ec == std::errc::file_exists)的初始代码将无法正常工作.

This means my initial code that checks if (ec == std::errc::file_exists) does not work if I don't use the generic category.

这是预期的行为吗?

推荐答案

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

This is a bug recently fixed in latest GCC 6, 7 and 8 point releases. It'll work as you expect if you're on the latest point release. See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=60555.

这篇关于error_code:如何设置和检查errno的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 04:44