首页 > 系统相关 >笔记整理--C语言--linux下错误的捕获:errno和strerror的使用——转载

笔记整理--C语言--linux下错误的捕获:errno和strerror的使用——转载

时间:2023-08-18 09:22:11浏览次数:33  
标签:__ No -- errno strerror LIBC include define

linux下错误的捕获:errno和strerror的使用

经常在调用linux系统api的时候会出现一些错误,比方说使用open()、write()、creat()之类的函数有些时候会返回-1,也就是调用失败,这个时候往往需要知道失败的原因。这个时候使用errno这个全局变量就相当有用了。
在程序代码中包含 #include <errno.h>, 然后每次程序调用失败的时候,系统会自动用用错误代码填充errno这个全局变量,这样你只需要读errno这个全局变量就可以获得失败原因了。
例如:

#include <stdio.h>
#include <string.h>
#include <errno.h>
int main(void)
{
    int fd;
    extern int errno;

    if((fd = open("/dev/dsp",O_WRONLY)) < 0) {
       printf("errno=%d\n",errno);
    }

    exit(0);
}

如果dsp设备忙的话errno值将是16。

errno.h中定义的错误代码值如下:
查看错误代码errno是调试程序的一个重要方法。当linuc C api函数发生异常时,一般会将errno变量(需include errno.h)赋一个整数值,不同的值表示不同的含义,可以通过查看该值推测出错的原因。在实际编程中用这一招解决了不少原本看来莫名其妙的问题。
比较麻烦的是每次都要去linux源代码里面查找错误代码的含义,现在把它贴出来,以后需要查时就来这里看了。
以下来自linux 2.4.20-18的内核代码中的/usr/include/asm/errno.h

点击查看代码
#ifndef _I386_ERRNO_H
#define _I386_ERRNO_H
#define EPERM   1 /* Operation not permitted */
#define ENOENT   2 /* No such file or directory */
#define ESRCH   3 /* No such process */
#define EINTR   4 /* Interrupted system call */
#define EIO       5 /* I/O error */
#define ENXIO   6 /* No such device or address */
#define E2BIG   7 /* Arg list too long */
#define ENOEXEC   8 /* Exec format error */
#define EBADF   9 /* Bad file number */
#define ECHILD 10 /* No child processes */
#define EAGAIN 11 /* Try again */
#define ENOMEM 12 /* Out of memory */
#define EACCES 13 /* Permission denied */
#define EFAULT 14 /* Bad address */
#define ENOTBLK 15 /* Block device required */
#define EBUSY 16 /* Device or resource busy */
#define EEXIST 17 /* File exists */
#define EXDEV 18 /* Cross-device link */
#define ENODEV 19 /* No such device */
#define ENOTDIR 20 /* Not a directory */
#define EISDIR 21 /* Is a directory */
#define EINVAL 22 /* Invalid argument */
#define ENFILE 23 /* File table overflow */
#define EMFILE 24 /* Too many open files */
#define ENOTTY 25 /* Not a typewriter */
#define ETXTBSY 26 /* Text file busy */
#define EFBIG 27 /* File too large */
#define ENOSPC 28 /* No space left on device */
#define ESPIPE 29 /* Illegal seek */
#define EROFS 30 /* Read-only file system */
#define EMLINK 31 /* Too many links */
#define EPIPE 32 /* Broken pipe */
#define EDOM 33 /* Math argument out of domain of func */
#define ERANGE 34 /* Math result not representable */
#define EDEADLK 35 /* Resource deadlock would occur */
#define ENAMETOOLONG 36 /* File name too long */
#define ENOLCK 37 /* No record locks available */
#define ENOSYS 38 /* Function not implemented */
#define ENOTEMPTY 39 /* Directory not empty */
#define ELOOP 40 /* Too many symbolic links encountered */
#define EWOULDBLOCK EAGAIN /* Operation would block */
#define ENOMSG 42 /* No message of desired type */
#define EIDRM 43 /* Identifier removed */
#define ECHRNG 44 /* Channel number out of range */
#define EL2NSYNC 45 /* Level 2 not synchronized */
#define EL3HLT 46 /* Level 3 halted */
#define EL3RST 47 /* Level 3 reset */
#define ELNRNG 48 /* Link number out of range */
#define EUNATCH 49 /* Protocol driver not attached */
#define ENOCSI 50 /* No CSI structure available */
#define EL2HLT 51 /* Level 2 halted */
#define EBADE 52 /* Invalid exchange */
#define EBADR 53 /* Invalid request descriptor */
#define EXFULL 54 /* Exchange full */
#define ENOANO 55 /* No anode */
#define EBADRQC 56 /* Invalid request code */
#define EBADSLT 57 /* Invalid slot */
#define EDEADLOCK EDEADLK
#define EBFONT 59 /* Bad font file format */
#define ENOSTR 60 /* Device not a stream */
#define ENODATA 61 /* No data available */
#define ETIME 62 /* Timer expired */
#define ENOSR 63 /* Out of streams resources */
#define ENONET 64 /* Machine is not on the network */
#define ENOPKG 65 /* Package not installed */
#define EREMOTE 66 /* Object is remote */
#define ENOLINK 67 /* Link has been severed */
#define EADV 68 /* Advertise error */
#define ESRMNT 69 /* Srmount error */
#define ECOMM 70 /* Communication error on send */
#define EPROTO 71 /* Protocol error */
#define EMULTIHOP 72 /* Multihop attempted */
#define EDOTDOT 73 /* RFS specific error */
#define EBADMSG 74 /* Not a data message */
#define EOVERFLOW 75 /* Value too large for defined data type */
#define ENOTUNIQ 76 /* Name not unique on network */
#define EBADFD 77 /* File descriptor in bad state */
#define EREMCHG 78 /* Remote address changed */
#define ELIBACC 79 /* Can not access a needed shared library */
#define ELIBBAD 80 /* Accessing a corrupted shared library */
#define ELIBSCN 81 /* .lib section in a.out corrupted */
#define ELIBMAX 82 /* Attempting to link in too many shared libraries */
#define ELIBEXEC 83 /* Cannot exec a shared library directly */
#define EILSEQ 84 /* Illegal byte sequence */
#define ERESTART 85 /* Interrupted system call should be restarted */
#define ESTRPIPE 86 /* Streams pipe error */
#define EUSERS 87 /* Too many users */
#define ENOTSOCK 88 /* Socket operation on non-socket */
#define EDESTADDRREQ 89 /* Destination address required */
#define EMSGSIZE 90 /* Message too long */
#define EPROTOTYPE 91 /* Protocol wrong type for socket */
#define ENOPROTOOPT 92 /* Protocol not available */
#define EPROTONOSUPPORT 93 /* Protocol not supported */
#define ESOCKTNOSUPPORT 94 /* Socket type not supported */
#define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */
#define EPFNOSUPPORT 96 /* Protocol family not supported */
#define EAFNOSUPPORT 97 /* Address family not supported by protocol */
#define EADDRINUSE 98 /* Address already in use */
#define EADDRNOTAVAIL 99 /* Cannot assign requested address */
#define ENETDOWN 100 /* Network is down */
#define ENETUNREACH 101 /* Network is unreachable */
#define ENETRESET 102 /* Network dropped connection because of reset */
#define ECONNABORTED 103 /* Software caused connection abort */
#define ECONNRESET 104 /* Connection reset by peer */
#define ENOBUFS 105 /* No buffer space available */
#define EISCONN 106 /* Transport endpoint is already connected */
#define ENOTCONN 107 /* Transport endpoint is not connected */
#define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */
#define ETOOMANYREFS 109 /* Too many references: cannot splice */
#define ETIMEDOUT 110 /* Connection timed out */
#define ECONNREFUSED 111 /* Connection refused */
#define EHOSTDOWN 112 /* Host is down */
#define EHOSTUNREACH 113 /* No route to host */
#define EALREADY 114 /* Operation already in progress */
#define EINPROGRESS 115 /* Operation now in progress */
#define ESTALE 116 /* Stale NFS file handle */
#define EUCLEAN 117 /* Structure needs cleaning */
#define ENOTNAM 118 /* Not a XENIX named type file */
#define ENAVAIL 119 /* No XENIX semaphores available */
#define EISNAM 120 /* Is a named type file */
#define EREMOTEIO 121 /* Remote I/O error */
#define EDQUOT 122 /* Quota exceeded */
#define ENOMEDIUM 123 /* No medium found */
#define EMEDIUMTYPE 124 /* Wrong medium type */
#endif

同时也可以使用strerror() 来自己翻译
如:

#include <stdio.h>
#include <string.h>
#include <errno.h>
int main(void)
{
   int   fd;
   extern int errno;

   if((fd = open("/dev/dsp",O_WRONLY)) < 0) {
      printf("errno=%d\n",errno);
      char * mesg = strerror(errno);
      printf("Mesg:%s\n",mesg);
   }

   exit(0);
}

dsp设备忙的话将输出如下:
errno=16
Mesg:Device or resource busy

linux中c语言errno的使用

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

errno会返回一个数字,每个数字代表一个错误类型。详细的可以查看头文件。/usr/include/asm/errno.h
如何把errno的数字转换成相应的文字说明?

可以使用strerrno函数

char *strerror(int errno)

使用方式如下:

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;
}

标签:__,No,--,errno,strerror,LIBC,include,define
From: https://www.cnblogs.com/stlong/p/17637502.html

相关文章

  • QtWebChannel和JavaScript进行通信(简单理解)
    说明在使用Qt(C++)和JavaScript之间实现通信时,通常会使用一些模块和技术来使两者能够交互和传递数据。这种通信通常用于在Qt应用程序中嵌入Web内容,或者在Web页面中嵌入Qt应用程序。以下是一些常用的模块和技术,以及它们的作用QtWebEngine模块:作用:QtWebEngine是Qt中的Web引擎,允......
  • 系统运维------------------系统调优12项操作(掌握)
    LINUX服务器日常运维12条操作原则原创 imoonrong Python运维实践 2023-04-0614:18 发表于河北收录于合集#Python运维实践428个#LINUX系统115个  Python运维实践Python运维实践,专注于互联网技术的总结与交流,内容涉及Python自动化运维、Django框架......
  • 30个shell脚本简单示例
    30个简单且常用的LinuxShell脚本命令及示例,有用~~时代Java 2023-08-1807:40 发表于北京↑ 点击上面 “时代Java”关注我们,关注新技术,学习新知识!shell一直是类Unix系统的本地命令行解释器。它已被证明是Unix的主要功能之一,并发展成为一个全新的主题。Linux提供了各......
  • OpenCV3.2图像分割 实例7:基于分水岭图像分割
    1#include<opencv2/opencv.hpp>2#include<iostream>34usingnamespacecv;5usingnamespacestd;67MatwatershedCluster(Mat&image,int&numSegments);8//参数分别为分割后图像,分割块数,输入原图9voidcreateDisplaySegments(Mat&se......
  • linux查看系统挂载磁盘
    linux查看系统挂载磁盘 解决AWS挂载、解决挂载完重启就消失等问题linux上的盘和window的有区别,磁盘空间必须挂载在目录上,要不然没用对与新增的硬盘、SSD固态硬盘、挂载到linux上的操作如下: df-h   #显示目前在Linux系统上的文件系统的磁盘使用情况统计。......
  • OpenCV3.2图像分割 实例8:Grabcut原理与演示应用
    1#include<opencv2/opencv.hpp>2#include<iostream>3#include<math.h>45usingnamespacecv;6usingnamespacestd;78intnumRun=0;9Rectrect;10boolinit=false;11Matsrc,image;12Matmask,bgMo......
  • GoLand 2023(GO语言集成开发工具环境)mac版
    GoLand是一个非常简单的Go语言开发工具,它使您能够在各种平台上构建Go应用程序。在过去的几年里,GoLand2023在各个领域进行了改进,并且继续发展。我们从这篇文章开始,以了解GoLand的新功能。GoLand的一个很棒的功能是允许您设置源代码,而不仅仅是编译它。这使您可以在编写代码之前......
  • HTML5中form如何关闭自动完成功能
    什么是HTML5的form自动完成功能?首先,HTML5中有个新属性autocomplete,autocomplete属性规定表单是否应该启用自动完成功能,它自动完成允许浏览器预测对字段的输入。当用户在字段开始键入时,浏览器基于之前键入过的值,应该显示出在字段中填写的选项。如:<form autocomplete="on">......
  • Alfred 5(最好用的mac效率工具)
    如果你用了一段时间的Mac,但是却还是不太熟悉Alfred,那这篇文章就是专门为你写的。Alfred是Mac上非常好用的效率工具,可以将你从繁重的工作中解放出来,让你可以更专注地工作。Alfred在Mac上的使用体验非常棒,除了各种快捷操作外,Alfred还有很多隐藏功能,这些功能也能极大地提升工作......
  • 三维模型OSGB格式轻量化技术在大规模场景的加载和渲染的作用分析
    三维模型OSGB格式轻量化技术在大规模场景的加载和渲染的作用分析  在移动设备上,大规模场景的加载和渲染是一个不容忽视的问题。对于OSGB格式轻量化处理来说,大规模场景的加载和渲染也是其中一项重要的任务。本文将重点分析OSGB格式轻量化处理在大规模场景的加载和渲染中发挥......