函数strerror与strerror_r


       #include <string.h>
       char *strerror(int errnum);
       int strerror_r(int errnum, char *buf, size_t n);

函数strerrorstrerror_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中。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM