Linux编程—出错处理之assert,abort,exit,atexit,strerror

已放弃

使用assert的缺点是,频繁的调用会极大的影响程序的性能,增加额外的开销。

在调试结束后,可以通过在包含#include <assert.h>的语句之前插入#define NDEBUG来禁用assert调用,示例代码如下:

#include <stdio.h>

#define NDEBUG

#include <assert.h>

用法总结与注意事项:

1)在函数开始处检验传入参数的合法性

如:

int resetBufferSize(int nNewSize)

{

//功能:改变缓冲区大小,

//参数:nNewSize缓冲区新长度

//返回值:缓冲区当前长度

//说明:保持原信息内容不变nNewSize<=0表示清除缓冲区

assert(nNewSize >= 0);

assert(nNewSize <= MAX_BUFFER_SIZE);

}

2)每个assert只检验一个条件,因为同时检验多个条件时,如果断言失败,无法直观的判断是哪个条件失败

不好: assert(nOffset>=0 && nOffset+nSize<=m_nInfomationSize);

好: assert(nOffset >= 0);

assert(nOffset+nSize <= m_nInfomationSize);

3)不能使用改变环境的语句,因为assert只在DEBUG个生效,如果这么做,会使用程序在真正运行时遇到问题

错误: assert(i++ <100)

这是因为如果出错,比如在执行之前i=100,那么这条语句就不会执行,那么i++这条命令就没有执行。

正确: assert(i <100)

i++;

4)assert和后面的语句应空一行,以形成逻辑和视觉上的一致感

5)有的地方,assert不能代替条件过滤

2.abort()

函数名:abort

功能:异常终止一个进程

用法: voidabort(void);

头文件:#include <stdlib.h>

说明:abort函数是一个比较严重的函数,当调用它时,会导致程序异常终止,而不会进行一些常规的清除工作,比如释放内存等。

程序例:

#include <stdio.h>

#include <stdlib.h>

int main(void)

{

puts( "About toabort….\n" );

abort();

puts( "This will never be executed!\n" );

exit( EXIT_SUCCESS );

}

[root@localhost error_process]# gccabort.c

[root@localhost error_process]# ./a.out

About toabort….

已放弃

3.exit()

表头文件:#include<stdlib.h>

定义函数:void exit(int status);

exit()用来正常终结目前进程的执行,并把参数status返回给父进程,而进程所有的缓冲区数据会自动写回并关闭未关闭的文件。

它并不像abort那样不做任何清理工作就退出,而是在完成所有的清理工作后才退出程序。

4.atexit(设置程序正常结束前调用的函数)

表头文件#include<stdlib.h>

定义函数int atexit (void (*function)(void));

atexit()用来设置一个程序正常结束前调用的函数。当程序通过调用exit()或从main中返回时,参数function所指定的函数会先被调用,然后才真正由exit()结束程序。

返回值如果执行成功则返回0,否则返回-1,失败原因存于errno中。

#include <stdlib.h>

#include <stdio.h>

void my_exit(void)

{

printf( "Before exit….\n" );

}

int main(void)

{

atexit( my_exit );

return 0;

}

[root@localhost error_process]# gcc atexit.c

[root@localhost error_process]# ./a.out

Before exit….

5.strerror(返回错误原因的描述字符串)

表头文件#include<string.h>

定义函数char * strerror(int errnum);

strerror()用来依参数errnum的错误代码来查询其错误原因的描述字符串,然后将该字符串指针返回。这时如果把errno传个strerror,就可以得到可读的提示信息,而不再是一个冷冰冰的数字了。

返回值返回描述错误原因的字符串指针。

#include <string.h>

#include <stdio.h>

int main(void)

{

int i;

for ( i=0; i<10; i++ )

{

printf( "%d:%s\n", i, strerror(i) );

}

return 0;

}

[root@localhost error_process]# gcc strerror.c

[root@localhost error_process]# ./a.out

0:Success

1:Operation not permitted

2:No such file or directory

3:No such process

4:Interrupted system call

5:Input/output error

6:No such device or address

7:Argument list too long

8:Exec format error

9:Bad file descriptor

[root@localhost error_process]#

如果爱,请深爱;如不爱,请离开。

Linux编程—出错处理之assert,abort,exit,atexit,strerror

相关文章:

你感兴趣的文章:

标签云: