perror实现分析(2.0: 具体实现)
来源:互联网 发布:centos php5.6 lamp 编辑:程序博客网 时间:2024/04/30 22:38
需要用到的结构(错误号,及对应的详细信息)
struct Pair { int code; const char* msg;};
生成错误信息数组:
struct Pair _sys_error_strings[] = {#define __BIONIC_ERRDEF(x,y,z) { x, z },#include "./_errdefs.h" { 0, NULL }};
_errdefs.h 的大概内容如下:
__BIONIC_ERRDEF( 0 , 0, "Success" )
__BIONIC_ERRDEF( EPERM , 1, "Operation not permitted" )
__BIONIC_ERRDEF( ENOENT , 2, "No such file or directory" )
__BIONIC_ERRDEF( ESRCH , 3, "No such process" )
const char* __strerror_lookup(int error_number) { return __code_string_lookup(_sys_error_strings, error_number);}
根据错误号查找对应的详细信息:
int strerror_r(int error_number, char* buf, size_t buf_len) { int saved_errno = errno; size_t length; const char* error_name = __strerror_lookup(error_number); if (error_name != NULL) { length = snprintf(buf, buf_len, "%s", error_name); } else { length = snprintf(buf, buf_len, "Unknown error %u", error_number); } if (length >= buf_len) { errno = ERANGE; return -1; } errno = saved_errno; return 0;}
函数原型,为了编译的时候不出错函数名修改为 myperror ,
void myperror(const char *prefix){ char buff[256]={0x00}; mystrerror_r( errno, buff, sizeof(buff) ); printf("buff is %s",buff); if (prefix) { write( 2, prefix, strlen(prefix) ); write( 2, ": ", 2 ); } write( 2, buff, strlen(buff) ); write( 2, "\n", 1 );}
在看看具体的应用实例:
#include <errno.h>#include <unistd.h>#include <fcntl.h>#include <sys/types.h>#include <sys/stat.h>#include <stdlib.h>#include <string.h>int main(){ int fd; fd = open("/dev/really_no_exists", O_RDWR); if(fd<0) { perror("perror"); myperror("myperror "); }}
输出:
myperror : No such file or directory
perror : No such file or directory
与ubuntu系统实现的效果一致:
参考:
bionic/libc/bionic/strerror_r.cpp
bionic/libc/include/sys/_errdefs.h
- perror实现分析(2.0: 具体实现)
- perror实现分析(1.0: 使用实例)
- perror实现分析(3.0: Linux支持的系统错误)
- Java中ArrayList具体实现分析1
- 分布式数据库的具体实现与对比分析
- 分布式数据库的具体实现与对比分析
- 分布式数据库的具体实现与对比分析
- 分布式数据库的具体实现与对比分析
- 分布式数据库的具体实现与对比分析
- u-boot分析。 关于start_armboot()函数的具体实现
- Android语音识别的具体实现实例特点分析
- ARM 架构 dump_stack 实现分析(1.0 具体实例)
- Launcher3源码分析 — bindScreen的具体实现
- Launcher3源码分析 — bindWorkspaceItems的具体实现
- OpenStack消息队列AMQP技术具体实现 [分析基于icehouse]
- 分析一下前端分页机制的具体实现
- laravel 用户登录分析以及登录限流的具体实现
- LinearLayoutCompat的源码分析分割线的具体实现
- HDOJ2015 偶数求和
- 2011斯坦福大学iOS应用开发教程学习笔记(第一课)MVC.and.Introduction.to.Objective-C
- 看懂SqlServer查询计划
- 网站建设与SEO--1,网站建设的初始准备
- 练习赛5.昆虫繁殖
- perror实现分析(2.0: 具体实现)
- 如何实现一个文件系统(六)
- shell中case的用法学习笔记
- hdu1215七夕节 筛素数+素因子分解+乘法公式
- spring集成Junit4配置
- BUS_ATTR(....)基础意义
- ubuntu 11.04的启动流程(启动服务的配置)
- 2011斯坦福大学iOS应用开发教程学习笔记(第二课)My First iOS App
- 【iOS开发必收藏】详解iOS应用程序内使用IAP/StoreKit付费、沙盒(SandBox)测试、创建测试账号流程!【2012-12-11日更新获取"产品付费数量等于0的问题"】