找回密码
 注册
搜索
查看: 958|回复: 0

[讨论] 如何使用exit和atexit终止程序?

[复制链接]
发表于 2012-8-1 16:58:03 | 显示全部楼层 |阅读模式
通用程序库提供了一些终止程序执行的方法,这些方法不同于通常从函数main返回以结束程序的方法。函数exit将强制程序结束,就好像程序被正常结束一样,这个函数通常用于在检测到输入错误时终止程序,或者程序无法打开要处理的文件时使用,函数atexit用来注册函数,这个函数将在成功结束程序时自动调用,成功结束程序是指到达main的末尾结束,或者调用了exit。

函数atexit用函数指针作为参数,这个函数不能有参数,也不能有返回值,最多可以注册32个要执行的函数。

函数exit有一个参数,这个参数通常是符号常量EXIT-SUCCESS或者符号常量EXIT_SUCCESS或者符号常量EXUT_FAILURE。如果用EXIT_SUCCESS调用了exit,则向调用环境返回表示成功结束的值。如果用EXIT_FAILURE调用了exit,则将返回表示不成功结束的值,在调用函数exit时,在前面用atexit注册的所有函数都将按照注册的逆序调用,所有与程序相关的流都将清空和关闭,然后控制制权返回的到外部环境。程序提示用户决定程序应该用exit结束,还是通过达到main结尾而结束,注意,在每次程序终止时都执行了函数print。里仁教育嵌入式培训职业讲师详情列出,这样更加明白理解:

/*使用函数exit和atexit */

#include

#include

Void print(void); //函数原型

Int main()

{

  Int answer;  //用户菜单选择

  Atexit(print); //注册print函数

Printf(“enter 1to termainate program with function exit”“\nenter 2to terminate program normally\n”);

//如果answer为1则调用exit

If(answer==1)

{

  Printf(“\nterminating program with function exit\n”);

  Exit(EXIT_success);

}//结束if

Printf(“\nterminating program by reaching the end of main\n”);

  Return 0; //表示程序成功结束

}//函数main结束

//在退出之前显示信息

Void print(void)

{

       Printf(“executing function print at program”“termination\n program terminated\n”);

}//结束函数print

Enter 1 to terminate program with function exit

Enter 2 to terminate program normally

1

Terminating program with function exit

Execution function print at program termination

Program terminated

Enter 1 terminate program with function exit

Enter 2 terminate program normally

2

Terminating program by reaching the end of main

Execting function print at program termination

Program terminated
www.lirenedu.org
高级模式
B Color Image Link Quote Code Smilies

本版积分规则

Archiver|手机版|小黑屋|52RD我爱研发网 ( 沪ICP备2022007804号-2 )

GMT+8, 2024-10-9 12:31 , Processed in 0.046574 second(s), 16 queries , Gzip On.

Powered by Discuz! X3.5

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表