Linux系统编程之错误处理:errno和perror,strerror
来源:互联网 发布:php打印实心菱形 编辑:程序博客网 时间:2024/05/16 07:01
Linux系统下错误处理方法:使用errno变量。头文件: errno.h
在系统出现错误时内核把错误写入到变量errno中。用户的应用程序可以从这个变量中获取错误的原因。
注意在系统调用返回失败时,必须紧接着引用errno变量,以避免程序中的下一条系统调用时覆盖errno的值。
errno的值可以格式化使出,使用错误处理函数 : perror strerror。
perror和strerror函数都是用来打印错误提示信息的。
perror:将错误信息出处到终端。
strerror:将错误信息输出到指定的缓冲区
它们的原型分别是:
perror:#include <stdio.h>void perror(const char *s);它先打印s指向的字符串,然后输出当前errno值所对应的错误提示信息,例如当前errno若为12,调用perror("ABC"),会输出"ABC: Cannot allocate memory"。测试程序:#include <stdio.h>#include <unistd.h>int main(void){ int fd = 10; int ret; ret = close(fd); if(ret == -1) perror("close error"); return 0;}测试结果:close error: Bad file descriptorstrerror:#include <string.h>char *strerror(int errnum);它返回errnum的值所对应的错误提示信息,例如errnum等于12的话,它就会返回"Cannot allocate memory"。测试程序:#include <stdio.h>#include <string.h>#include <unistd.h>#include <errno.h>int main(void){ int fd = 10; int ret; ret = close(fd); if(ret == -1) fprintf(stderr, "close error with msg is: %s\n",strerror(errno)); return 0;}测试结果:close error with msg is: Bad file descriptor
0 0
- linux系统编程之错误处理:perror,strerror和errno
- Linux系统编程之错误处理:perror,strerror和errno
- Linux系统编程之错误处理:perror,strerror和errno
- Linux系统编程之错误处理:errno和perror,strerror
- Linux系统编程之错误处理:perror,strerror和errno
- 关于Linux系统编程的错误处理:errno、perror、strerror
- Linux系统编程之错误处理:perror,strerror和errno http://www.linuxidc.com/Linux/2013-07/87238.htm
- Linux系统编程:errno,perror,strerror
- Linux/Unix C编程之perror函数,strerror函数,errno
- linux下错误的捕获:errno、perror和strerror的使用
- linux下错误的捕获:errno、strerror和perror的使用
- [Linux/Unix C 编程] perror函数,strerror函数,errno
- Linux/Unix C编程之的perror函数,strerror函数,errno
- Linux学习 之 perror函数,strerror函数,errno
- 玩玩linux下的errno, perror, strerror
- errno、stderr、perror函数和strerror函数
- errno、stderr、perror函数和strerror函数
- errno、stderr、perror函数和strerror函数
- 当前iframe调用另一个iframe中的元素以及方法
- 【NOIP 模拟题】[T1]连锁店(贪心)
- openwrt添加SSH等应用
- 脱水缩合(字符串处理)
- java语言基础复习03
- Linux系统编程之错误处理:errno和perror,strerror
- 键值对数组如何按照"键"进行排序?
- 开源Andord库集锦
- myeclipse10配置tomcat详细过程
- Google Zxing 二维码生成与解析
- 各浏览器中自定义滚动条的样式
- Android中怎样用@ViewInject注解来彻底放弃findViewByid,gogoog0!!!
- 树结构练习——判断给定森林中有多少棵树
- 在阅读了Nodejs文档后我学到的19件事