(转)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 ...
随机推荐
- POJ 2828 Buy Tickets(线段树单点)
https://vjudge.net/problem/POJ-2828 题目意思:有n个数,进行n次操作,每次操作有两个数pos, ans.pos的意思是把ans放到第pos 位置的后面,pos后面的 ...
- HTML+CSS设计个人主页
在个人主页的设计中,我采用了圣代布局和div分块.效果图如下: <!DOCTYPE html> <html lang="en"> <head> ...
- Java统计文件中字母个数
import java.text.DecimalFormat; import java.io.File; import java.io.FileReader; import java.io.Buffe ...
- PHP中操作数据库的预处理语句
今天这篇文章的内容其实也是非常基础的内容,不过在现代化的开发中,大家都使用框架,已经很少人会去自己封装或者经常写底层的数据库操作代码了.所以这回我们就来复习一下数据库中相关扩展中的预处理语句内容. 什 ...
- 如何创建 Office LTSC 2021 VL(批量许可)版本的安装 ISO
Office LTSC 2021 发布 2021 年 9 月 16 日,微软正式发布了支持 Office 2021 的部署工具(Office Deployment Tool),这意味着 Office ...
- sql case when 多条件小结
sql case when 多条件 小结 -- 第一种 格式 : 简单Case函数 : -- 格式说明 -- case 列名 -- when 条件值1 then 选择项1 -- when 条件值2 t ...
- 『Python』优雅的记录日志——loguru
1. 安装 pip install loguru 2. 初识 from loguru import logger logger.debug("This is a debug..." ...
- Redis之品鉴之旅(三)
3)Set,可以去重的.无序的集合.可以取交集.并集.zset(sorted set),有序的.去重的集合,排序不是根据value排序,而是根据score排序. using (RedisClient ...
- Redis基础数据结构-基于2.8
SDS SDS是Redis中String的底层数据结构,数据结构如下,SDS保留了传统的C字符串表达方式即数组的最后一个元素是'/0'结尾.此外还添加了两个字段len和free,其中len表示字符串长 ...
- 题解 CF1172E Nauuo and ODT
题目传送门 题目大意 给出一个 \(n\) 个点的树,每个点有颜色,定义 \(\text{dis}(u,v)\) 为两个点之间不同颜色个数,有 \(m\) 次修改,每次将某个点的颜色进行更改,在每次操 ...