处理退出时指定的函数。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函数不应包含任何依赖于可能已卸载了时的任何 DLL atexit调用函数。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
atexitatexit <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
exit、_Exit、_exitexit, _Exit, _exit
_onexit、_onexit_m_onexit, _onexit_m