通过atexit调用函数,可以再main函数return之后再执行刚刚被调用的函数。
msdn解释是:The atexit function is passed the address of a function (func) to be called when the program terminates normally. Successive calls to atexit create a register of functions that are executed in last-in, first-out (LIFO) order. The functions passed to atexit cannot take parameters. 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创建一个LIFO的函数寄存器。在程序正常结束之后,函数才被调用。且由于是LIFO,因此执行调用顺序与书写顺序相反。
程序如下:

#include <stdio.h>

#include <stdlib.h>

int a;

void exit_fn1(void)

{
  a ++;

   printf("Exit function #1 called: %d\n", a);

}

void exit_fn2(void)

{
  a ++;

   printf("Exit function #2 called: %d\n", a);

}

int main(void)

{
   a = 0;

   /* post exit function #1 */

   atexit(exit_fn1);

   /* post exit function #2 */

   atexit(exit_fn2);
   
   a = 5;

   return 0;

}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-12
  • 2021-06-03
猜你喜欢
  • 2022-12-23
  • 2021-11-14
  • 2021-05-22
  • 2022-12-23
  • 2022-12-23
  • 2022-01-30
  • 2022-12-23
相关资源
相似解决方案