在C/C++大型项目中,错误管理在项目中起着举足轻重的作用,以我自己的项目经验以及观摩其他项目,错误管理对项目框架以及开发效率有着很大的影响。对于错误管理的认识大致分为三类:
- 刚刚开始写程序的新手,满篇程序看不到一处关于返回出错的处理,更不用说出错管理了。说明他没认识到出错管理的重要性
- 程序中到处都能看到关于出错的处理。认识到了错误,但是处理方式欠缺
- 程序中几乎不会很明显的看到关于错误的处理。这是错误管理的最高境界。
错误管理,涉及到程序的健壮性,可恢复性,可靠性,高效性。在出错的情况下,程序任然能够相对稳健高效的执行。
下面我谈谈我自己在C/C++项目开发中关于错误管理的经验。
对于C/C++系统API,都提供了errno.h头文件,里面已经定义了绝大多数系统已知的错误以及其对应的错误提示。 参考《linux中出错处理》
一般系统自带的错误定义以及出错提示都不能很好的满足实际的项目需求,毕竟项目中很多都涉及到具体业务,如果笼统的使用系统定义的错误号以及描述,并不能很快的定义错误位置。通常需要我们自己重新封装并定义错误。
《The Art of Unix Programming》中有一个原则说的非常好:Rule of Repair: When you must fail, fail noisily and as soon as possible。当程序遇到无法修复必须报错的时候,就让它立即用很明显的方式报错。这句话很简洁,但是缺描述出了关于错误管理的理念。如果一定要出错,就很明显的方式来表达,目的就是为了很迅速精准的定位错误。出错不是期望,出错管理也不是目的,目的是为了在出错之后能很快的定位错误使得程序能够很快的恢复。
为了快速定位错误,有三个宏非常有用:
- __FILE__ //文件名
- __FUNCTION__ //函数名
- __LINE__ //当前行号
一般针对不同的业务会有不同的模块。自定义错误号的方式如下:
- //EBASE最高位是1,保证错误号是负数,符合编程习惯
- #define EBASE 0X80000000
- //串口业务模块
- #define ESERIAL EBASE + 0XC8
- #define ESERIALTIMEOUT ESERIAL + 1 //串口超时
- #define ESERIALREAD ESERIAL + 2 //读串口错误
- //....
- //HTTP业务模块,与ESERIAL之间有200的差距,这样串口业务模块可以有200个错误号
- #define EHTTPSERVICE EBASE + 0X190
- #define EHTTPTIME EHTTPSERVICE + 1
- #define EHTTPGET EHTTPSERVICE + 2
- //...
- //与EHTTPSERVICE有200差距,这样HTTP也可以有200个错误号
- #define EGSM EBASE + 258
- //....
模块化定义错误,通过错误号区间可以很快的查阅错误模块。例如错误号是 -202,通过对照,毫无疑问是串口模块出错了。
接下来就是错误的翻译了。所谓错误翻译就是将错误号翻译成具体的语句。可以选择将错误描述与错误号写入Excel表中,然后导出XML文件,在程序中错误描述可以直接解析对应XML中错误号的描述即可。
另一种比较常见的方式就是直接用宏写在一个头文件中。当然,__FILE__, __FUNCTION__这些必不可少。
日志文件记录了程序后台运行状况以及出错前一刻程序正在做什么,一般可以从日志文件的数据分析程序的行为并定位错误。对于日志文件,我想C/C++程序员都会写,这里我就不多说。一般打印错误提示的同时都会伴随着写日志。
一般都会用宏来写打印错误和写日志的操作,关于如何写我这里不多说,我想很多人都会。这里我想强调的事关于打印错误信息和写日志一定要设置开关。在实际项目中,我经常会遇到这种问题,当有很多地方都需要打印和记录log的时候,程序执行的非常慢,当我把写日志去掉,程序立马就能很快的运行。所以,设置开关是很有必要的:
- #ifndef LOG_OFF
- #define WriteLog(file, line, function, desc) \
- //...一些写日志和打印操作
- #else
- #define WriteLog(file, line, function, desc)
- #endif
这样,在程序中可以很好的控制开关。提高效率
linux中,在支持多线程的环境中,通常每个线程都有属于自己的errno变量,是用来表示特定错误的常量。
以下是<errno.h>中定义的所有出错errno常量
#define EPERM 1 /* Operation not permitted */
#define ENOENT 2 /* No such file or directory */
#define ESRCH 3 /* No such process */
#define EINTR 4 /* Interrupted system call */
#define EIO 5 /* I/O error */
#define ENXIO 6 /* No such device or address */
#define E2BIG 7 /* Argument list too long */
#define ENOEXEC 8 /* Exec format error */
#define EBADF 9 /* Bad file number */
#define ECHILD 10 /* No child processes */
#define EAGAIN 11 /* Try again */
#define ENOMEM 12 /* Out of memory */
#define EACCES 13 /* Permission denied */
#define EFAULT 14 /* Bad address */
#define ENOTBLK 15 /* Block device required */
#define EBUSY 16 /* Device or resource busy */
#define EEXIST 17 /* File exists */
#define EXDEV 18 /* Cross-device link */
#define ENODEV 19 /* No such device */
#define ENOTDIR 20 /* Not a directory */
#define EISDIR 21 /* Is a directory */
#define EINVAL 22 /* Invalid argument */
#define ENFILE 23 /* File table overflow */
#define EMFILE 24 /* Too many open files */
#define ENOTTY 25 /* Not a typewriter */
#define ETXTBSY 26 /* Text file busy */
#define EFBIG 27 /* File too large */
#define ENOSPC 28 /* No space left on device */
#define ESPIPE 29 /* Illegal seek */
#define EROFS 30 /* Read-only file system */
#define EMLINK 31 /* Too many links */
#define EPIPE 32 /* Broken pipe */
#define EDOM 33 /* Math argument out of domain of func */
#define ERANGE 34 /* Math result not representable */
#define EDEADLK 35 /* Resource deadlock would occur */
#define ENAMETOOLONG 36 /* File name too long */
#define ENOLCK 37 /* No record locks available */
#define ENOSYS 38 /* Function not implemented */
#define ENOTEMPTY 39 /* Directory not empty */
#define ELOOP 40 /* Too many symbolic links encountered */
#define EWOULDBLOCK EAGAIN /* Operation would block */
#define ENOMSG 42 /* No message of desired type */
#define EIDRM 43 /* Identifier removed */
#define ECHRNG 44 /* Channel number out of range */
#define EL2NSYNC 45 /* Level 2 not synchronized */
#define EL3HLT 46 /* Level 3 halted */
#define EL3RST 47 /* Level 3 reset */
#define ELNRNG 48 /* Link number out of range */
#define EUNATCH 49 /* Protocol driver not attached */
#define ENOCSI 50 /* No CSI structure available */
#define EL2HLT 51 /* Level 2 halted */
#define EBADE 52 /* Invalid exchange */
#define EBADR 53 /* Invalid request descriptor */
#define EXFULL 54 /* Exchange full */
#define ENOANO 55 /* No anode */
#define EBADRQC 56 /* Invalid request code */
#define EBADSLT 57 /* Invalid slot */
#define EDEADLOCK EDEADLK 58
#define EBFONT 59 /* Bad font file format */
#define ENOSTR 60 /* Device not a stream */
#define ENODATA 61 /* No data available */
#define ETIME 62 /* Timer expired */
#define ENOSR 63 /* Out of streams resources */
#define ENONET 64 /* Machine is not on the network */
#define ENOPKG 65 /* Package not installed */
#define EREMOTE 66 /* Object is remote */
#define ENOLINK 67 /* Link has been severed */
#define EADV 68 /* Advertise error */
#define ESRMNT 69 /* Srmount error */
#define ECOMM 70 /* Communication error on send */
#define EPROTO 71 /* Protocol error */
#define EMULTIHOP 72 /* Multihop attempted */
#define EDOTDOT 73 /* RFS specific error */
#define EBADMSG 74 /* Not a data message */
#define EOVERFLOW 75 /* Value too large for defined data type */
#define ENOTUNIQ 76 /* Name not unique on network */
#define EBADFD 77 /* File descriptor in bad state */
#define EREMCHG 78 /* Remote address changed */
#define ELIBACC 79 /* Can not access a needed shared library */
#define ELIBBAD 80 /* Accessing a corrupted shared library */
#define ELIBSCN 81 /* .lib section in a.out corrupted */
#define ELIBMAX 82 /* Attempting to link in too many shared libraries */
#define ELIBEXEC 83 /* Cannot exec a shared library directly */
#define EILSEQ 84 /* Illegal byte sequence */
#define ERESTART 85 /* Interrupted system call should be restarted */
#define ESTRPIPE 86 /* Streams pipe error */
#define EUSERS 87 /* Too many users */
#define ENOTSOCK 88 /* Socket operation on non-socket */
#define EDESTADDRREQ 89 /* Destination address required */
#define EMSGSIZE 90 /* Message too long */
#define EPROTOTYPE 91 /* Protocol wrong type for socket */
#define ENOPROTOOPT 92 /* Protocol not available */
#define EPROTONOSUPPORT 93 /* Protocol not supported */
#define ESOCKTNOSUPPORT 94 /* Socket type not supported */
#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */
#define EPFNOSUPPORT 96 /* Protocol family not supported */
#define EAFNOSUPPORT 97 /* Address family not supported by protocol */
#define EADDRINUSE 98 /* Address already in use */
#define EADDRNOTAVAIL 99 /* Cannot assign requested address */
#define ENETDOWN 100 /* Network is down */
#define ENETUNREACH 101 /* Network is unreachable */
#define ENETRESET 102 /* Network dropped connection because of reset */
#define ECONNABORTED 103 /* Software caused connection abort */
#define ECONNRESET 104 /* Connection reset by peer */
#define ENOBUFS 105 /* No buffer space available */
#define EISCONN 106 /* Transport endpoint is already connected */
#define ENOTCONN 107 /* Transport endpoint is not connected */
#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */
#define ETOOMANYREFS 109 /* Too many references: cannot splice */
#define ETIMEDOUT 110 /* Connection timed out */
#define ECONNREFUSED 111 /* Connection refused */
#define EHOSTDOWN 112 /* Host is down */
#define EHOSTUNREACH 113 /* No route to host */
#define EALREADY 114 /* Operation already in progress */
#define EINPROGRESS 115 /* Operation now in progress */
#define ESTALE 116 /* Stale NFS file handle */
#define EUCLEAN 117 /* Structure needs cleaning */
#define ENOTNAM 118 /* Not a XENIX named type file */
#define ENAVAIL 119 /* No XENIX semaphores available */
#define EISNAM 120 /* Is a named type file */
#define EREMOTEIO 121 /* Remote I/O error */
#define EDQUOT 122 /* Quota exceeded */
#define ENOMEDIUM 123 /* No medium found */
#define EMEDIUMTYPE 124 /* Wrong medium type */
#define ECANCELED 125 /* Operation Canceled */
#define ENOKEY 126 /* Required key not available */
#define EKEYEXPIRED 127 /* Key has expired */
#define EKEYREVOKED 128 /* Key has been revoked */
#define EKEYREJECTED 129 /* Key was rejected by service */
/* for robust mutexes */
#define EOWNERDEAD 130 /* Owner died */
#define ENOTRECOVERABLE 131 /* State not recoverable */
对于errno的应用,应该知道两条规则:
第一,如果没有出错,则其值不会被一个例程清除。也即是如果没有出错,errno的值将不会被修改。
第二,任意一个函数都不会将errno值设置为0。
C标准定义了两个函数,帮助打印出错信息。
- #include <string.h>
- char *strerror(int errnum)
- //这个函数返回errno值所对应的字符串指针。errnum就是errno所定义的常量
此函数映射为出错消息字符串,并返回该字符串指针。
此函数的一般用法如下:
fprintf(stderr, " EACCS:%s/n", strerror(EACCES)); //其中,stderr标准出错文件描述符,就是将信息显示在屏幕上
- #include <stdio.h>
- void perror(const char *msg);
- //perror函数基于error的当前值,在标准出错上产生一条信息,然后返回
它首先输出由msg指向的字符串,然后是一个冒号,一个空格,接着是对应于errno值的出错消息,最后是一个换行符。
一般情况下是strerror和perror连用。
如果只使用perror函数,那么它会自动在出错消息字符串之后显示errno值的出错信息
格式如下 string: errno的字符串/n
这样有可能是打印上一次的错误信息。所以,在使用perror函数之前要确保errno被赋值到特定的错误编号。