Linux系统函数失败后都会返回一个负值,并且整形变量errno通常被设置为错误码。我们在使用错误码时,需要包含如下头文件
#include <errno.h>
errno只在函数返回错误时才有意义,当函数执行正常返回时并不会重置errno,因此此时的errno是不能作为错误处理的。
errno是一个int型变量,除了直接使用该变量,还有两个和其相关的API可以方便的查看错误类型:
#include <stdio.h>
void perror(const char *msg);
这个函数会先打印msg信息,然后再输出对应的error类型。
#include <string.h>
char *strerror(int errno);
这个函数把errno字符串化,输出对应的错误类型字符串。
示例
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main(int argc, char *argv[])
{
errno = EINVAL;
printf("Error:%s, errno:%d\n", strerror(errno), errno);
perror(argv[0]);
exit(0);
}
运行结果:
$ gcc error.c -o error
$ ./error
Error:Invalid argument, errno:22
./error: Invalid argument