2

当经典的 linux c/c++ 软件出现问题时,我们有一个神奇的变量 errno,它为我们提供了刚刚出错的线索。

但是这些错误是在哪里定义的?

让我们举个例子(它实际上是 Qt 应用程序的一部分,因此是 qDebug())。

if (ioctl(file, I2C_SLAVE, address) < 0) {
    int err = errno;
    qDebug() << __FILE__ << __FUNCTION__ << __LINE__ 
        << "Can't set address:" << address
        << "Errno:" << err << strerror(err);
     ....

下一步是查看 errno 是什么,以便我们决定是退出还是尝试解决问题。

所以我们可能会在这一点上添加一个 if 或 switch。

if (err == 9)
{
    // do something...
}
else 
{
    //do someting else
}

我的问题是在哪里可以找到“9”代表的错误?我不喜欢我的代码中那种神奇的数字。

/谢谢

4

4 回答 4

13

它们通常在/usr/include/errno.h* 中定义,并且可以通过包含 errno.h 来访问:

#include <errno.h>

我在报告错误时写出 errno 值及其文本含义,通过以下方式获取文本含义strerror()

if (something_went_wrong)
{
    log("Something went wrong: %s (%d)", strerror(errno), errno);
    return false;
}

但是,在 Linux shell 中,您可以使用该perror实用程序找出不同的 errno 值的含义:

$ perror 9
OS error code   9:  Bad file descriptor

编辑:您的代码应更改为使用符号值:

if (err == EBADF)
{
    // do something...
}
else 
{
    //do someting else
}

编辑2:*至少在Linux下,实际值是在/usr/include/asm-generic/{errno,errno-base}.h其他地方定义的,如果你想查看它们,找到它们有点痛苦。

于 2011-03-15T15:25:19.623 回答
1
NAME
       errno - number of last error

SYNOPSIS
       #include <errno.h>

DESCRIPTION
       The  <errno.h>  header file defines the integer variable errno, which is set by system calls and some library functions in the event of an error to indicate
       what went wrong.  Its value is significant only when the return value of the call indicated an error (i.e., -1 from most system calls; -1 or NULL from  most
       library functions); a function that succeeds is allowed to change errno.

       Valid error numbers are all non-zero; errno is never set to zero by any system call or library function.
于 2011-03-15T15:26:05.940 回答
1

通常要实现错误处理,您需要知道函数可以返回哪些特定的错误代码。此信息可在 man 或http://www.kernel.org/doc/man-pages/中获得。

例如,对于 ioctl 调用,您应该期望以下代码:

   EBADF  d is not a valid descriptor.

   EFAULT argp references an inaccessible memory area.

   EINVAL Request or argp is not valid.

   ENOTTY d is not associated with a character special device.

   ENOTTY The specified request does not apply to the kind of object that the
          descriptor d references.

编辑:如果<errno.h>包含所有定义所有可能错误代码的文件,那么您实际上并不需要知道它们的确切位置。

于 2011-03-15T15:36:43.633 回答
0

该文件是:

/usr/include/errno.h

--p

于 2011-03-15T15:27:58.870 回答