处理退出时指定的函数。Processes the specified function at exit.


int atexit(  
   void (__cdecl *func )( void )  


要调用的函数。Function to be called.

返回值Return Value

如果成功,则 atexit 返回 0;如果发生错误,则返回非零值。atexit returns 0 if successful, or a nonzero value if an error occurs.


当程序正常终止时,向 atexit 函数传递要调用的函数 (func) 的地址。The atexit function is passed the address of a function (func) to be called when the program terminates normally. atexit 的后续调用将创建一个函数注册表,其中的函数按后进先出 (LIFO) 顺序执行。Successive calls to atexit create a register of functions that are executed in last-in, first-out (LIFO) order. 传递到 atexit 的函数不能接受参数。The functions passed to atexit cannot take parameters. atexit_onexit 使用堆保存函数注册表。atexit and _onexit use the heap to hold the register of functions. 因此,可以注册的函数的数量仅受堆内存限制。Thus, the number of functions that can be registered is limited only by heap memory.

atexit 函数中的代码不应该包含在调用 atexit 函数时已卸载的任何 DLL 上的任何依赖项。The code in the atexit function should not contain any dependency on any DLL which could have already been unloaded when the atexit function is called.

要生成符合 ANSI 的应用程序,请使用 ANSI 标准的 atexit 函数(而不是类似的 _onexit 函数)。To generate an ANSI-compliant application, use the ANSI-standard atexit function (rather than the similar _onexit function).


例程Routine 必需的标头Required header
atexit <stdlib.h><stdlib.h>


调用 atexit 时,该程序将四个函数推送到要执行的函数堆栈。This program pushes four functions onto the stack of functions to be executed when atexit is called. 当程序退出时,这些程序以后进先出的方式执行。When the program exits, these programs are executed on a last in, first out basis.

// crt_atexit.c  
#include <stdlib.h>  
#include <stdio.h>  

void fn1( void ), fn2( void ), fn3( void ), fn4( void );  

int main( void )  
   atexit( fn1 );  
   atexit( fn2 );  
   atexit( fn3 );  
   atexit( fn4 );  
   printf( "This is executed first.\n" );  

void fn1()  
   printf( "next.\n" );  

void fn2()  
   printf( "executed " );  

void fn3()  
   printf( "is " );  

void fn4()  
   printf( "This " );  
This is executed first.  
This is executed next.  

请参阅See Also

进程和环境控制 Process and Environment Control
abort abort
exit、_Exit、_exit exit, _Exit, _exit
_onexit、_onexit_m_onexit, _onexit_m