Chinaunix首页 | 论坛 | 博客
  • 博客访问: 55559
  • 博文数量: 22
  • 博客积分: 1546
  • 博客等级: 上尉
  • 技术积分: 230
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-20 20:33
文章分类
文章存档

2010年(22)

分类: LINUX

2010-07-24 11:30:21

之前我写过一个关于linux下C编程中错误捕获函数的,即我们可以自己编写一个函数来捕获一些错误,让程序员处理错误的时候更简单。如果将这个函数放入error.h头文件中,那么以后就可以直接调用了。本文便是和大家一起讨论如何将自己编写的错误捕获函数放入头文件error.h中。

头文件放在/usr/include目录下,进入这个目录,然后用vi编辑器打开error.h文件。要添加的两个函数如下:

void my_err1(int error)
{
	printf("error:  %s with errno: %d\n",strerror(error),error);
	exit(1);
}
void my_err2(const char* err_string,int line,int error)
{
	printf("error:  line:%d %s():%s with errno:%d\n",line,err_string,strerror(error),error);
        exit(1);
}

将上述两函数添加至文件末尾。由于strerror()函数涉及到头文件string.h,所以在已打开的error.h文件中还得添加string.h头文件。具体添加位置可参考下面:

 20 #ifndef _ERROR_H
 21 #define _ERROR_H 1
 22
 23 #include "features.h"
 24
 25 //personal addition
 26 #include "string.h"
 27 //personal addition end
 28
 29 __BEGIN_DECLS
 30

 59 //personal addition
 60 //brief function
 61 void my_err1(int error)
 62 {
 63                 printf("error:  %s with errno: %d\n",strerror(error),error);
 64                 exit(1);
 65 }
 66
 67 //detailed function
 68 void my_err2(const char* err_string,int line,int error)
 69 {
 70                 printf("error:  line:%d %s():%s with errno:%d\n",line,err_string,strerror(error),error);
 71                 exit(1);
 72 }
 73 //persoanl addition end
 74 __END_DECLS
 75
 76 #endif /* error.h */

其中my_err1和my_err2显示的错误信息稍有不同。添加好后就可以保存了。但是现在问题来了:按照平时我们的保存方法:wq保存时,会提示:E45: 已设定选项 'readonly' (请加 ! 强制执行)。这是因为头文件属于系统文件,linux为了安全起见,不允许普通用户对其进行修改。我们可以用ls -l查看其属性:

edsionte@edsionte-laptop:/usr/include$ ls -l error.h
-rw-r--r-- 1 root root 2557 2010-06-23 12:11 error.h

从上面的文件存取权限可以看出,root用户可以对其读写,root所在的root组可对其读,其他组用户只可对其读。现在我们更改这个文件的权限,让非root用户可对其修改。

edsionte@edsionte-laptop:/usr/include$ sudo chmod 777 error.h
[sudo] password for edsionte:
edsionte@edsionte-laptop:/usr/include$ ls -l error.h
-rwxrwxrwx 1 root root 2557 2010-06-23 12:11 error.h

修改好权限后,就可以用上面的方法对error.h文件进行修改并保存。
下面进行测试:
测试源码如下。

#include “errno.h”
#include “fcntl.h“
#include "unistd.h”
#include "stdlib.h“
#include "stdio.h”
#include ”sys/types.h“
#include “sys/stat.h”
#include ”string.h“
#include “error.h”

int main()
{
	int fd;
	if((fd=open("example_test.c",O_CREAT|O_EXCL,S_IRUSR|S_IWUSR))==-1)
	{
		my_err1(errno);
//		my_err2("open",__LINE__,errno);
	}
	close(fd);
	return 0;
}
}

首先测试my_err1,结果如下:

edsionte@edsionte-laptop:~/code$ ./my_error
error:  File exists with errno: 17

然后将my_err1注释掉,测试my_err2,结果如下:

edsionte@edsionte-laptop:~/code$ ./my_error
error:  line:17 open():File exists with errno:17

结果和前面介绍捕获函数时的测试结果一样。你以为现在就结束了吗?当然没有,我们要把error.h头文件的权限修改成原样。

edsionte@edsionte-laptop:/usr/include$ sudo chmod 644 error.h
[sudo] password for edsionte:
edsionte@edsionte-laptop:/usr/include$ ls -l error.h
-rw-r--r-- 1 root root 2557 2010-06-23 12:50 error.h

大功告成。

阅读(623) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~