atexit()函数积累记录

本文详细介绍了C/C++标准库中的atexit函数,该函数用于在程序正常终止前注册并调用指定的函数。文章解释了atexit函数的工作原理、参数及返回值,并通过示例演示了如何使用该函数。此外,还探讨了atexit函数的一些限制条件。
函数名: atexit
头文件:#include<stdlib.h>
功 能: 注册终止函数(即main执行结束后调用的函数)
用 法: int atexit(void (*func)(void));
注意:按照ISO C的规定,一个进程可以登记多达32个函数,这些函数将由exit自动调用。atexit()注册的函数类型应为不接受任何参数的void函数,exit调用这些注册函数的顺序与它们 登记时候的顺序相反。同一个函数如若登记多次,则也会被调用多次。

C++11的原文解释:

Set function to be executed on exit
The function pointed by func is automatically called without arguments when the program terminates normally.

If more than one atexit function has been specified by different calls to this function, they are all executed in reverse order as a stack (i.e. the last function specified is the first to be executed at exit).

A single function can be registered to be executed at exit more than once.

If atexit is called after exit, the call may or may not succeed depending on the particular system and library implementation ( unspecified behavior).

If a function registered with atexit throws an exception for which it does not provide a handler when called on termination, terminate is automatically called (C++).

Particular library implementations may impose a limit on the number of functions call that can be registered with atexit, but this cannot be less than 32 function calls.


最后一句话很关键:but this cannot be less than 32 function calls.不能少于32个,而不是网上一些“最多32个”的说法,翻译成“多达32个函数”,也是模棱两可。

Parameters

function
Function to be called. The function shall return no value and take no arguments.

Return Value

A zero value is returned if the function was successfully registered.
If it failed, a non-zero value is returned.


官方example:

/* atexit example */
#include <stdio.h>      /* puts */
#include <stdlib.h>     /* atexit */

void fnExit1 (void)
{
  puts ("Exit function 1.");
}

void fnExit2 (void)
{
  puts ("Exit function 2.");
}

int main ()
{
  atexit (fnExit1);
  atexit (fnExit2);
  puts ("Main function.");
  return 0;
}

Output:


Main function.
Exit function 2.
Exit function 1.





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值