[Linux]出错处理errno

概述

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

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

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

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

Linux

为了避免多线程环境共享一个errno,Linux系统定义了一个宏来解决这个问题

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

示例

#include <error.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.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

猜你喜欢

转载自www.cnblogs.com/yiyide266/p/10627392.html