如何將錯誤號轉換為「errno」常數?

如何將錯誤號轉換為「errno」常數?

假設我有一個在 UNIX 機器上運行的應用程式失敗,系統錯誤狀態為「13」。現在,我可以輕鬆地在 errno.h 中找到該值,發現這是一個權限被拒絕的問題。

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

有沒有更簡單的命令來檢索此資訊?我希望能夠運行這樣的東西:

> lookuperror 13
EACCES (Permission denied)

而不是 grep 系統頭檔。這樣的命令/程式存在嗎?

更新: 正如下面的答案所指出的,strerror()系統呼叫會傳回此資訊。是否有任何 UNIX 作業系統附帶可執行此系統調用的實用程序,或者我是否需要編寫自己的程式來執行此操作?

答案1

我用來做

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

您可以將 Perl 程式碼放入檔案中並將其放在路徑中。
當然也可以用C來完成

答案2

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

答案3

嘗試 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.

答案4

cpp -dM預處理原始檔或頭檔並列印#define它找到的每個文件。它比 grep through 更強大/usr/include/errno.h,因為它會取得/usr/include/errno.h包含的每個檔案。

結合 cpp -dM 和其他人的建議:

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

插入到 .bashrc,或將其內容作為獨立的 shell 腳本放置。

相關內容