main主函数执行完毕后,是否可能再执行一段代码??5 C x$ v- G9 A# K5 S2 y* I" M
书上说使用atexit函数注册一个函数.有一段代码:
, R* v. @4 {% L$ ^ #include <iostream.h>1 |) s$ f/ _8 D! d( h/ K1 _
#include <stdlib.h>
. A$ E. ?% g5 B #include<stdio.h>5 T+ M4 e! h# j/ l
int atexit(void (*function)(void));3 x; F2 Y. O$ \$ P% b
#include <string.h>
- A- E6 e% q# @5 p* {1 T3 ~1 h #include<stdlib.h>
6 t4 G# w8 t0 }5 h$ d #include <stdio.h>3 }2 W/ ^% j w, a* Y" y6 e
void fn1(void),fn2(void),fn3(void),fn4(void); O+ {, `$ [8 ~* z$ _! x, k7 k
int main(void)
. f2 B: m% L6 {$ t* _; ?4 a- v9 n {9 Q& V, y( \% g, \% T" T( N9 _
atexit(fn1);3 q7 Y9 h! J2 g) v* K% j* B
atexit(fn2);
( [3 E+ `5 e. H; {* X atexit(fn3);
! Q$ E) p# _/ W- K3 h3 | atexit(fn4);
' k! f5 b" |- g. l' \ printf("This is executed first.\n");
. z' m# L u! V2 z. `3 X( n m //return 0;) u; v% _9 r4 d* ^+ p
}
5 D! t3 n: L/ Q; ]* Z; P8 {) @ void fn1()( g+ s* X$ a4 _% S' r2 D- @) i% E2 X
{
z) b2 J/ L5 N( t/ L- u) L; u printf("next.\n");
2 e7 Z& Q3 a( D$ R } b4 ?# C8 C3 _
void fn2()1 ?" G- ?4 V2 G. {, \; ^( H7 t$ `( Z
{5 w' H2 e# t& l7 j! m( _
printf("executed ");
4 ]! f* q1 X U3 h4 ^ }
' ?! S7 _7 O, ?, D9 g void fn3()
: Y4 J# ?: o' Q; } {% g: Q& k! i4 S* j& K0 F. z/ g. h
printf("is ");: ?1 I- t7 Q- E
}
5 Q" {/ N! E5 z# c. ^- G void fn4(); E+ v* m4 O2 t, h* O" G: f
{ M& K l7 t. H
printf("This ");
/ H( l4 H& K) z4 E }. w! X! {( i$ b, e. H
结果:8 v0 J( \. A8 `) ~4 w( w
This is executed first.
# y" c$ x1 {1 u+ E; U This is executed next.
3 W7 m4 w3 h% o6 @2 f# | 我不大明白为什么输出:This is executed next,而不是next executed is this.
7 o$ z z7 R: [$ G 也不大明白注册的函数怎么调用的? l9 ~( }3 x$ X A2 k
main函数退出后,会在调用exit函数,而exit函数里对依次调用atexit注册的函数,不过调用顺序是和atexit注册顺序相反的。