zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    cocos2d游戏jsc文件格式解密,SpideMonkey大冒险
    抖音下载短视频去水印方法
    Metaspliot技术
    WAF bypass
    博客园美化
    Redis未授权访问利用
    网站后台getshell
    OpenVAS
    跨站脚本攻击与防御总结
    相同浏览器同一浏览器多用户登录问题
  • 原文地址:https://www.cnblogs.com/yiyide266/p/10627392.html
Copyright © 2011-2022 走看看