zoukankan      html  css  js  c++  java
  • linux中c语言errno的使用

    在linux中使用c语言编程时,errno是个很有用的动动。他可以把最后一次调用c的方法的错误代码保留。但是如果最后一次成功的调用c的方法,errno不会改变。因此,只有在c语言函数返回值异常时,再检测errno。

    errno会返回一个数字,每个数字代表一个错误类型。详细的可以查看头文件。/usr/include/asm/errno.h

    如何把errno的数字转换成相应的文字说明?
    方式一:可以使用strerrno函数

    char*strerror(interrno)

    使用方式如下:

    fprintf(stderr,"error in CreateProcess %s, Process ID %d ",strerror(errno),processID)

    将错误代码转换为字符串错误信息,可以将该字符串和其它的信息组合输出到用户界面。
    注:假设processID是一个已经获取了的整形ID

    方式二:使用perror函数

    void perror(const char *s)

    函数说明
    perror ( )用来将上一个函数发生错误的原因输出到标准错误(stderr),参数s 所指的字符串会先打印出,后面再加上错误原因 字符串。此错误原因依照全局变量 errno 的值来决定要输出的字符串。

    另外并不是所有的c函数调用发生的错误信息都会修改errno。例如gethostbyname函数。

    errno是否是线程安全的?
    errno是支持线程安全的,而且,一般而言,编译器会自动保证errno的安全性。
    我们看下相关头文件 /usr/include/bits/errno.h
    会看到如下内容:

    # if !defined _LIBC || defined _LIBC_REENTRANT
    /* When using threads, errno is a per-thread value. */
    # define errno (*__errno_location ())
    # endif
    # endif /* !__ASSEMBLER__ */
    #endif /* _ERRNO_H */

    也就是说,在没有定义__LIBC或者定义_LIBC_REENTRANT的时候,errno是多线程/进程安全的。
    为了检测一下你编译器是否定义上述变量,不妨使用下面一个简单程序。

    #include <stdio.h>
    #include <errno.h>
     
    int main( void )
    {
    #ifndef __ASSEMBLER__
            printf( "Undefine __ASSEMBLER__/n" );
    #else
            printf( "define __ASSEMBLER__/n" );
    #endif
     
    #ifndef __LIBC
            printf( "Undefine __LIBC/n" );
    #else
            printf( "define __LIBC/n" );
    #endif
     
    #ifndef _LIBC_REENTRANT
            printf( "Undefine _LIBC_REENTRANT/n" );
    #else
            printf( "define _LIBC_REENTRANT/n" );
    #endif
     
            return 0;
    }
  • 相关阅读:
    UVa OJ 148 Anagram checker (回文构词检测)
    UVa OJ 134 LoglanA Logical Language (Loglan逻辑语言)
    平面内两条线段的位置关系(相交)判定与交点求解
    UVa OJ 130 Roman Roulette (罗马轮盘赌)
    UVa OJ 135 No Rectangles (没有矩形)
    混合函数继承方式构造函数
    html5基础(第一天)
    js中substr,substring,indexOf,lastIndexOf,split等的用法
    css的textindent属性实现段落第一行缩进
    普通的css普通的描边字
  • 原文地址:https://www.cnblogs.com/yanenquan/p/3776712.html
Copyright © 2011-2022 走看看