#include <string.h>
char *strerror(int errnum);
int strerror_r(int errnum, char *buf, size_t n);
函數strerror和strerror_r均是根據錯誤碼得到對應的錯誤描述。
但是strerror_r是更加安全的版本 因為它有用戶自己提供描述錯誤信息的緩存。
strerror_r 成功返回0 失敗返回 -1 並設置errno
在linux編程中,strerror()是個好東東,因為一個孤零零的errno看不出個所以然,然而strerror()返回的錯誤描述已經給我們解決問題提供了80%的成功率。但從安全性的角度來講,strerror_r是更好的選擇,因為:
#include <string.h>
char *strerror(int errnum);
int strerror_r(int errnum, char *buf, size_t n);
說明,對於函數strerror_r,第一個參數errnum是錯誤代碼,第二個參數buf是用戶提供的存儲錯誤描述的緩存,第三個參數n是緩存的大小。
DESCRIPTION
The strerror() function returns a string describing the error code passed in the argument errnum, possibly using the LC_MESSAGES part of the current locale to select the appropriate language. This string must not be modified by the application, but may be modified by a subsequent call to perror() or strerror(). No library function will modify this string.
The strerror_r() function is similar to strerror(), but is thread safe. It returns the string in the user-supplied buffer buf of length n.
RETURN VALUE
The strerror() function returns the appropriate error description string, or an unknown error message if the error code is unknown. The value of errno is not changed for a successful call, and is set to a nonzero value upon error. The strerror_r() function returns 0 on success and -1 on failure, setting errno.
用man strerror_r在Fedora 5 中可以看到該函數存在於glibc2.0及以上版本中。它的好處是可以把錯誤描述放在用戶自定義的buffer中。