[转]用atexit()处理C/C++程序的退出

来源:互联网 发布:在线视频播放网站源码 编辑:程序博客网 时间:2024/06/07 01:32
用atexit()处理C/C++程序的退出
2007-11-25 17:55

与java中的addShutdownHook 函数类似。不过java中的hook好像就那一个?http://hi.baidu.com/dearfenix/blog/item/96e0acd3517375033af3cf19.html

 

 

    很多时候我们需要在程序退出的时候做一些诸如释放资源的操作,但程序退出的方式有很多种,比如main()函数运行结束、在程序的某个地方用exit() 结束程序、用户通过Ctrl+C或Ctrl+break操作来终止程序等等,因此需要有一种与程序退出方式无关的方法来进行程序退出时的必要处理。方法就 是用atexit()函数来注册程序正常终止时要被调用的函数。

    atexit()函数的参数是一个函数指针,函数指针指向一个没有参数也没有返回值的函数。atexit()的函数原型是:int atexit (void (*)(void));

    在一个程序中最多可以用atexit()注册32个处理函数,这些处理函数的调用顺序与其注册的顺序相反,也即最先注册的最后调用,最后注册的最先调用。

下面是一段代码示例:
#include <stdlib.h> // 使用atexit()函数所必须包含的头文件stdlib.h
#include <iostream.h>

void terminate()


{
    cout<<"program is terminating now..."<<endl;
}

int main(void)
{
    // 注册退出处理函数
    atexit(terminate);

    cout<<"the end of main()"<<endl;

    return 0;
}

程序的运行结果为:
the end of main()
program is terminating now...

 

If you want to lock the computer, you can call this function:
LockWorkStation();

If you want to use Hot key, you can use this function:
BOOL RegisterHotKey(          HWND hWnd,
    int id,
    UINT fsModifiers,
    UINT vk
);

原创粉丝点击