atexit
函数名: atexit
头文件:#include<stdlib.h>
功 能: 注册终止函数(即main执行结束后调用的函数)
用 法: int atexit(void (*func)(void));
注意:按照ISO C的规定,一个进程可以登记多达32个函数,这些函数将由exit自动调用。atexit()注册的函数类型应为不接受任何参数的void函数,exit调用这些注册函数的顺序与它们 登记时候的顺序相反。同一个函数如若登记多次,则也会被调用多次。
程序例:
#include <stdio.h>
#include <
stdlib.h>
void exit_fn1(void)
{
printf("Exit function #1 called\n");
}
void exit_fn2(void)
{
printf("Exit function #2 called\n");
}
int main(void)
{
/* post exit function #1 */
atexit(exit_fn1);
/* post exit function #2 */
atexit(exit_fn2);
return 0;
}
输出:
Exit function #2 called
Exit function #1 called
进程的终止方式:
有8种方式使进程终止,其中前5种为正常终止,它们是
1:从 main 返回
2:调用 exit
3:调用 _exit 或 _Exit
4:最后一个线程从其启动例程返回
5:最后一个线程调用 pthread_exit
异常终止有3种,它们是
6:调用 abort
7:接到一个信号并终止
8:最后一个线程对取消请求做出响应
#include <stdlib.h?
void exit (int status);
void _Exit (int status);
#include <unistd.h>
void _exit (status);
其中调用 _exit,_Exit 都不会调用终止程序
异常终止也不会。
转载者注:该程序在ubuntu 12.04下无法运行 需要修改
void
(
*
__malloc_initialize_hook
)
(
void
)
=
my_mempool_init
;
为
void
(
*volatile
__malloc_initialize_hook
)
(
void
)
=
my_mempool_init
;
何谓钩子函数,当一个函数挂载了钩子函数后,你执行这个函数时,实际执行的是钩子函数。
linux下内存函数可以定义自己的钩子函数,好像网络通讯库函数也可以。
下面,我们来看内存函数的钩子函数,首先看定义(在/usr/include/malloc.h里)
linux下内存函数可以定义自己的钩子函数,好像网络通讯库函数也可以。
下面,我们来看内存函数的钩子函数,首先看定义(在/usr/include/malloc.h里)
1
2 3 4 5 6 7 8 9 10 11 12 13 |
extern
extern extern extern extern extern |
接下来看我写的一个实例
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
#include
#include #include static static static static static { } static { } static { } static { } static { } static { } static { } void int { } |
输出结果为
1
2 |
malloc size
:
free address : |
明显执行了钩子函数!