(转)linux下错误的捕获:errno和strerror的使用,以及perror和strerror的区别
经常在调用linux 系统api 的时候会出现一些错误,比方说使用open() write() creat()之类的函数有些时候会返回-1,也就是调用失败,这个时候往往需要知道失败的原因。这个时候使用errno这个全局变量就相当有用了。
在程序代码中包含 #include <errno.h>,然后每次程序调用失败的时候,系统会自动用用错误代码填充errno这个全局变量,这样你只需要读errno这个全局变量就可以获得失败原因了。
例如:
1 #include <stdio.h>
2 #include <string.h>
3 #include <errno.h>
4 int main(void)
5 {
6 int fd;
7 extern int errno;
8
9 if((fd = open("/dev/dsp",O_WRONLY)) < 0) {
10 printf("errno=%d\n",errno);
11 }
12
13 exit(0);
14 }
如果dsp设备忙的话errno值将是16。
errno.h中定义的错误代码值如下:
查看错误代码errno是调试程序的一个重要方法。当linux 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
转自:https://www.douban.com/note/165931644/
-----------------perror和sterror的区别-----------------
perror() 和 strerror() 以一种直观的方式打印出错误信息,对于调试程序和编写优秀的程序非常有用。
下面是perror() 与 strerror() 的使用范例及区别:
perror()原型:
#include <stdio.h>
void perror(const char *s);
其中,perror()的参数s 是用户提供的字符串。当调用perror()时,它输出这个字符串,后面跟着一个冒号和空格,然后是基于当前errno的值进行的错误类型描述(也就是刚刚内核代码宏定义里面的那一长串字符)。
strerror()原型:
#include <string.h>
char * strerror(int errnum);
这个函数将errno的值作为参数,并返回一个描述错误的字符串。
1 /*rename.c*/
2
3 #include<stdio.h>
4 #include <string.h>
5 #include <errno.h>
6
7 int main(int argc,char **argv)
8 {
9 char path[]="./first.c";
10 char newpath[] = "./second.c";
11 char newpathnot[] = "./gong/suo.c";
12 extern int errno;
13
14 if( rename(path,newpathnot) == 0)
15 {
16 printf("the file %s was moved to %s.",path,newpathnot);
17 }
18 else
19 {
20 printf("Can't move the file %s.\n",path);
21 printf("errno:%d\n",errno);
22 printf("ERR:%s\n",strerror(errno));
23 perror("Err");
24 }
25
26 if(rename(path,newpath) == 0)
27 printf("the file %s was moved to %s.\n",path,newpath);
28 else
29 {
30 printf("Can't move the file %s.\n",path);
31 printf("errno:%d\n",errno);
32 printf("ERR:%s\n",strerror(errno));
33 }
34
35 return 0;
36 }
37
38
39 gcc rename.c -o rename
40 ./rename
41
42 Can't move the file ./first.c.
43 errno:2
44 ERR:No such file or directory
45 Err: No such file or directory
46 the file ./first.c was moved to ./second.c
strerror()方法与perror()的用法十分相似。
先谈谈perror()的用法,这个方法用于将上一条语句(方法)执行后的错误打印到标准输出上。一般情况下(没有使用重定向的话),就是输出到控制台上。
但是,如果我需要了解另外一个进程的某一个方法执行的错误,或者更briefly,我就希望将错误打印到一个文件里面,perror()就不太合适了!
为了实现我刚刚说到的要求,我们首先要将错误放到一个字符串里面。这个时候,strerror()就合适了!
strerror(errno)
首先,系统会根据上一条语句的执行错误情况,将errno赋值.。关于这点,我们首先明白两点。第一,errno是一个系统变量,是不需要我们赋值或者声明的。第二,errno是一个int类型的变量,而且其中的值对应一种特定错误类型
然后,关于strerror()本身,可以这么理解。顾名思义,strerror=string+error,就是将errno值翻译成描述错误类型的string语句!
从上面的结果可以看出,perror(s),实际上是会输出s: strerror(errno)这样的形式,其中strerror(errno)表示errno对应的错误字符串。
转自:http://blog.csdn.net/callinglove/article/details/8301789
(转)linux下错误的捕获:errno和strerror的使用,以及perror和strerror的区别的更多相关文章
- linux下错误的捕获:errno(errno.h)和strerror(string.h)的使用
参考:http://blog.csdn.net/starstar1992/article/details/52756387 linux下错误的捕获:errno和strerror的使用 经常在调用lin ...
- linux下错误的捕获:errno和strerror的使用
经常在调用linux 系统api 的时候会出现一些错误,比方说使用open() write() creat()之类的函数有些时候会返回-1,也就是调用失败,这个时候往往需要知道失败的原因.这个时候使用 ...
- Linux下错误的捕获:全局变量errno和strerror()
经常在调用linux 系统api 的时候会出现一些错误,比方说使用open() write() creat()之类的函数有些时候会返回-1,也就是调用失败,这个时候往往需要知道失败的原因.这个时候使用 ...
- 转: linux下错误的捕获:errno和strerror的使用
经常在调用linux 系统api 的时候会出现一些错误,比方说使用open() write() creat()之类的函数有些时候会返回-1,也就是调用失败,这个时候往往需要知道失败的原因.这个时候使用 ...
- linux c 错误的捕获
经常在调用linux 系统api 的时候会出现一些错误,比方说使用open() write() creat()之类的函数有些时候会返回-1,也就是调用失败,这个时候往往需要知道失败的原因.这个时候使用 ...
- linux下错误 && 解决方法
1.使用yum命令安装出现错误 Error: Cannot find a valid baseurl for repo: extras 解决方法: vi /etc/resolv.conf 在此文件最后 ...
- Linux下gcc与gdb简介
gcc编译器可以将C.C++等语言源程序.汇编程序编译.链接成可执行程序.gdb是 GNU 开发的一个Unix/Linux下强大的程序调试工具. linux下没有后缀名的概念.但 gcc 根据文件的后 ...
- Linux的错误码表
Linux的错误码表(errno table): _ 124 EMEDIUMTYPE_ Wrong medium type_ 123 ENOMEDIUM__ No medium found_ 122 ...
- 【C/C++】Linux下system()函数引发的错误
http://my.oschina.net/renhc/blog/54582 [C/C++]Linux下system()函数引发的错误 恋恋美食 恋恋美食 发布时间: 2012/04/21 11:3 ...
随机推荐
- go案例:客户管理系统流程 mvc模式 分层设计
下面是一个简要的客服系统,主要是演示分层计.. model : 数据部份: package model import "fmt" //声明一个结构体,表示一个客户信息 type C ...
- ecshop二次开发秒杀、限时折扣、清仓等功能
限时抢购,秒杀商品的二次开发 1,先在后台admin/templates 中找goods_info.htm文件到促销部分,改为一个下拉列表的分别是促销,限时,秒杀,值分别是1,2,3这样,代码如下: ...
- no rxtxSerial in java.library.path
java开发过程中,遇到no rxtxSerial in java.library.path问题,是由于缺少一个dll文件导致. 在jre/bin下添加rxtxSerial.dll 文件 win10环 ...
- 使用jemeter构造各种变量数据
使用手动创建测试数据太麻烦,因此考虑用jmeter写了一些创建测试数据的脚本,针对那些变量非固定的数据可以利用函数来实现 通过函数助手添加各种变量数据 Tools--->函数助手 1:生成当前时 ...
- YbtOJ#526-折纸游戏【二分,hash】
正题 题目链接:https://www.ybtoj.com.cn/problem/526 题目大意 一个\(n\times m\)的网格上有字母,你每次可以沿平行坐标轴对折网格,要求对折的对应位置字母 ...
- hexo配合github action 自动构建(多种形式)
已经使用HEXO正常构建GitHub页面 根据github action 给hexo配置自动部署github page 前往墨抒颖的个人网站查看纯净版 1. 为仓库设置访问密钥 第一步先生成密钥,打开 ...
- 树莓派使用python+继电器控制220V灯泡
需要的材料 1.继电器:继电器是一种电控制器件,它实际上是用小电流去控制大电流运作的一种"自动开关",我们这里用它来控制电灯.控制了继电器就等于控制了电灯. 我购买的是某宝上3块钱 ...
- MySQL学习总结:提问式回顾 undo log 相关知识
原文链接:MySQL学习总结:提问式回顾 undo log 相关知识 1.redo 日志支持恢复重做,那么如果是回滚事务中的操作呢,也会有什么日志支持么? 也回滚已有操作,那么就是想撤销,对应的有撤销 ...
- 关于VS中的无法解析的外部符号问题
利用caffe的源码编译出的caffe.lib静态链接库里面就包含了源码里面的那些函数的接口i,所以如果在程序中使用的是源码的话,就不需要在链接器里面再添加此静态链接库了 对于无法解析的外部符号,首先 ...
- 自定义view---仪表盘--kotlin
我们知道一个自定义view一般来说需要继承view或者viewGroup并实现onMeasure, onLayout, onDraw方法. 其中onMeasure用于测量计算该控件的宽高, onLay ...