• [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 ", 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 ", my_errno); return 0; }

    以上代码输出:

    file error: Bad file descriptor
    9
    file error: No such file or directory
    2
  • 相关阅读:
    Servlet
    Web服务器和Tomcat
    DOM文档对象模型
    JavaScript总结
    CSS总结
    商城——购物车模块
    用户注册登录认证模块
    P2P技术之STUN、TURN、ICE详解
    P2P中的NAT穿越(打洞)方案详解
    NAT技术详解
  • 原文地址:https://www.cnblogs.com/yiyide266/p/10627392.html
Copyright © 2020-2023  润新知