[Linux]出错处理errno

概述

公共头文件<errno.h>定义了一个整型值errno以及可以赋予它的各种常量。

大部分函数出错后返回-1,并且自动给errno赋予当前发生的错误枚举值。

需要注意的一点是,errno只有在错误发生时才会被复写,这就意味着如果按顺序执行AB两个函数,如果只有A函数出错,则执行完AB函数后errno依然保留着A函数出错的枚举值,

如果AB均出错,那么在B之前如果errno没有被处理,那么将会被B出错的枚举值所覆盖。

 

Linux

为了避免多线程环境共享一个errno,Linux系统定义了一个宏来解决这个问题,这个定义已经定义在<errno.h>系统头文件中。

extern int *__errno_location(void);
#define errno (*__errno_location())

最让人疑惑的是,你可以为此宏赋值,具体解析可以参考这个文章

 

int main(void)
{
    errno = 1;
    perror("");
    errno = 2;
    perror("");
    return 0;
}

 

 

 

示例

#include <error.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>

/*Already define in <error.h>*/ /*extern int *__errno_location(void); #define errno (*__errno_location())*/ char buf[500000]; int main(void) { int re, my_errno; re = read(90, buf, sizeof(buf)); if(re > -1){ my_errno = 0; }else{ my_errno = errno; perror("file error"); } printf("%d\n", my_errno); re = 0; re = open("./not_exists_file", O_RDONLY); if(re > -1){ my_errno = 0; }else{ my_errno = errno; perror("file error"); } printf("%d\n", my_errno); return 0; }

以上代码输出:

file error: Bad file descriptor
9
file error: No such file or directory
2

 

errno列表:

含义 常量 函数
0
Success
   
1
Operation not permitted
   
2
No such file or directory
   
3
No such process
   
4
Interrupted system call
   
5
Input/output error
   
6
No such device or address
   
7
Argument list too long
   
8
Exec format error
   
9
Bad file descriptor
   
10
No child processes
   
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
       
posted @ 2019-03-30 15:02  yiyide266  阅读(1117)  评论(0编辑  收藏  举报