如果可能,请询问POSIX,否则请询问Linux专用平台:
errno
值?(对于信号SIGUSR1
和SIGUSR2
)errno
值?(负值?)strerror()
中断?(在strerror()
符号前检查?)我的代码errnum
资源,并通知另一个对象。如果发生故障(成功为零),则通知open()
会传达系统Event
。
但是也可以在我的代码中检测到失败,例如errno
。我想重用字段if(count>=size)
来传达此故障。因此,我的用户定义的故障代码不应与系统定义的Event::errnum
值重叠。
我找到了errno
,但这似乎特定于errno
range 9000–11000 reserved for user ...
注意,我的问题是关于errno
的不是。 Transaction Processing Facility没有暴露在我的代码之外。我的代码不会覆盖library-defined errno。
以下代码段位于struct Event
中,但我的问题也适用于errno
。
c++
实际c值未由C和C ++标准定义。因此,无法返回一个特定的(正)整数并保证它不会与实现使用的整数冲突。C标准只需要三个marco:
C11草稿,7.5错误
宏是
EDOM序列号范围
扩展为int类型的整数常量表达式,不同正值,适合在#if预处理中使用指令;
所以您不知道在实现中定义了其他#include <cerrno>
#define E_MY_USER_DEFINED_ERROR 9999
struct Event
{
int fd;
int errnum;
};
struct Foo
{
Foo( int sz ) : count(0), size(sz) {}
Event open( const char name[] )
{
if( count >= size )
return { -1, E_MY_USER_DEFINED_ERROR };
int fd = 1; // TODO: open ressource...
if (fd < 0) return { -1, errno };
else return { fd, 0 };
}
int count, size;
};
int main()
{
Foo bar(0);
Event e = bar.open("my-ressource");
// send Event to another object...
}
个值。
errno
值是标准C和POSIX中的正整数。因此,您可以使用自己的负数表示负号来定义自己的错误号。但是,那么您将无法使用strerror / perror接口。因此,您可能需要用于strerror / perror的附加包装器来解释您自己的错误号。
类似:
errno
和errno
的相似名称。
注意,在调用“开放资源”之前,还应将enum myErrors{
ERR1 = -1,
ERR2 = -2,
...
ERR64 = -64
};
char *my_strerror(int e)
{
if (e>=ERR1 && e<=ERR2)
return decode_myerror(e); // decode_myerror can have a map for
//your error numbers and return string representing 'e'.
else
return strerror(e);
}
设置为perror
,以确保确实由您的函数设置了errno
。
在这种情况下,我会完全避免使用标准的errno,并为错误定义自己的枚举。如果您的“开放资源”不太复杂,并且返回的错误代码太多,则可以这样做。
0
建议使用负值作为用户定义的范围。 这对我来说很完美。
以下是我的问题摘录,使用P.P.此代码段也可以在errno
上找到。
P.P.'s answer
使用GCC输出
coliru
使用Clang输出
#include <cerrno>
#include <cstring>
#include <iostream>
#define E_MY_USER_DEFINED_ERROR -1
struct Event
{
int fd;
int errnum;
};
struct Foo
{
Foo( int sz ) : count(0), size(sz) {}
Event open( const char name[] )
{
if( count >= size )
return { -1, E_MY_USER_DEFINED_ERROR };
int fd = std::strlen(name); // TODO: open ressource...
if (fd < 0) return { -1, errno };
else return { fd, 0 };
}
int count, size;
};
int main()
{
Foo bar(0);
Event e = bar.open("my-ressource");
std::cout << std::strerror( e.errnum ) << std::endl;
}