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
  • 相关阅读:
    设置Edittext全键盘
    Math中和角度,弧长,tan等相关的算法
    Android:TabLayout的一些设置
    Android;设置TextView加粗 代码设置
    Android:关于Edittext的一些设置
    Android:View颤抖的动画效果代码
    Android:dialog去除边框的实现(自带Style的padding)
    Android:自定义Dialog大小,显示圆角
    Android:EventBus
    SAS宏系统选项SYMBOLGEN MCOMPILENOTE MPRINT<NEST> MLOGIC(NEST)
  • 原文地址:https://www.cnblogs.com/yiyide266/p/10627392.html
Copyright © 2011-2022 走看看