我试图了解在调用设置的 C 函数时应该使用什么类别errno
在 Linux 上。
我不确定所有可能的错误代码都是由 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());
主要基于此讨论:
- 类别和标准/系统错误代码
- @niall-douglas 提供的代码示例:
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)
如果我不使用通用类别,则不起作用。
这是预期的行为吗?