如何将错误号码转换为“errno”常量?

假设我有一个在UNIX系统上运行的应用程序,系统错误状态为'13'。 现在,我可以很容易地在errno.h中查找这个值,发现这是一个权限被拒绝的问题。

> grep -w 13 /usr/include/errno.h #define EACCES 13 /* Permission denied */ 

有一个简单的命令来检索这些信息? 我想能够运行这样的东西:

 > lookuperror 13 EACCES (Permission denied) 

而不是系统头文件。 这样的命令/程序是否存在?

更新:正如在下面的答案中指出的, strerror()系统调用返回这个信息。 是否有任何UNIX操作系统附带一个可执行的实用程序,使这个系统调用,或者我需要编写自己的程序来做到这一点?

我用来做

 perl -MPOSIX -e 'print strerror($ARGV[0])."\n";' 13 

您可以将Perl代码放在一个文件中,并将其放在path中。
当然也可以用C来完成

 ~% perror 13 OS error code 13: Permission denied ~% rpm -qf =perror mysql-server-5.0.45-7.el5 

尝试strerror(3)。

从手册:

 DESCRIPTION The strerror(), strerror_r() and perror() functions look up the error message string corresponding to an error number. The strerror() function accepts an error number argument errnum and returns a pointer to the corresponding message string. The strerror_r() function renders the same result into strerrbuf for a maximum of buflen characters and returns 0 upon success. The perror() function finds the error message corresponding to the cur- rent value of the global variable errno (intro(2)) and writes it, fol- lowed by a newline, to the standard error file descriptor. If the argu- ment string is non-NULL and does not point to the null character, this string is prepended to the message string and separated from it by a colon and space (``: ''); otherwise, only the error message string is printed. If the error number is not recognized, these functions return an error message string containing ``Unknown error: '' followed by the error num- ber in decimal. The strerror() and strerror_r() functions return EINVAL as a warning. Error numbers recognized by this implementation fall in the range 0 < errnum < sys_nerr. If insufficient storage is provided in strerrbuf (as specified in buflen) to contain the error string, strerror_r() returns ERANGE and strerrbuf will contain an error message that has been truncated and NUL terminated to fit the length specified by buflen. The message strings can be accessed directly using the external array sys_errlist. The external value sys_nerr contains a count of the mes- sages in sys_errlist. The use of these variables is deprecated; strerror() or strerror_r() should be used instead. 

作为一个解决方法,你可以在你的shell中创build一个别名或函数:

例如。 .bashrc

 function lookuperror { grep -w "$@" /usr/include/errno.h } 

cpp -dM预处理源文件或头文件并打印find的每个#define 。 它比grep通过/usr/include/errno.h更强大,因为它会得到/usr/include/errno.h包含的每个文件。

将cpp -dM与其他人的build议结合起来:

 function lookuperror { cpp -dM /usr/include/errno.h | grep -w "$@" perl -MPOSIX -e 'print "Description:".strerror($ARGV[0])."\n";' $@ } 

插入.bashrc,或将其内容作为独立的shell脚本放置。