在linux中使用c语言编程时,errno是个很有用的动动。他可以把最后一次调用c的方法的错误代码保留。但是如果最后一次成功的调用c的方法,errno不会改变。因此,只有在c语言函数返回值异常时,再检测errno。
errno会返回一个数字,每个数字代表一个错误类型。详细的可以查看头文件。/usr/include/asm/errno.h
如何把errno的数字转换成相应的文字说明?
方式一:可以使用strerrno函数
1 | char * strerror ( int errno ) |
使用方式如下:
1 | fprintf (stderr, "error in CreateProcess %s, Process ID %d " , strerror ( errno ),processID) |
将错误代码转换为字符串错误信息,可以将该字符串和其它的信息组合输出到用户界面。
注:假设processID是一个已经获取了的整形ID
方式二:使用perror函数
1 | void perror ( const char *s) |
函数说明
perror ( )用来将上一个函数发生错误的原因输出到标准错误(stderr),参数s 所指的字符串会先打印出,后面再加上错误原因 字符串。此错误原因依照全局变量 errno 的值来决定要输出的字符串。
另外并不是所有的c函数调用发生的错误信息都会修改errno。例如gethostbyname函数。
errno是否是线程安全的?
errno是支持线程安全的,而且,一般而言,编译器会自动保证errno的安全性。
我们看下相关头文件 /usr/include/bits/errno.h
会看到如下内容:
if !defined _LIBC || defined _LIBC_REENTRANT
/* When using threads, errno is a per-thread value. */
define errno (*__errno_location ())
endif
endif /* !__ASSEMBLER__ */
#endif /* _ERRNO_H */
也就是说,在没有定义__LIBC或者定义_LIBC_REENTRANT的时候,errno是多线程/进程安全的。
为了检测一下你编译器是否定义上述变量,不妨使用下面一个简单程序。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <stdio.h> #include <errno.h> int main( void ) { #ifndef __ASSEMBLER__ printf ( "Undefine __ASSEMBLER__/n" ); #else printf ( "define __ASSEMBLER__/n" ); #endif #ifndef __LIBC printf ( "Undefine __LIBC/n" ); #else printf ( "define __LIBC/n" ); #endif #ifndef _LIBC_REENTRANT printf ( "Undefine _LIBC_REENTRANT/n" ); #else printf ( "define _LIBC_REENTRANT/n" ); #endif return 0; } |
技术交流

原文链接:linux中c语言errno的使用,转载请注明来源!