main函数执行完毕后,是否可能会再执行一段代码?
可以使用atexit()函数注册一个函数,代码如下:
代码
#include <cstdlib>
int atexit(void (*function)(void));
#include <cstdlib>
#include <cstdio>
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 ");
}
也可以使用_onexit()函数注册一个函数,代码如下:
代码
#include <cstdlib>
#include <cstdio>
int fn1(void), fn2(void), fn3(void), fn4(void);
int main(void)
{
_onexit(fn1);
_onexit(fn2);
_onexit(fn3);
_onexit(fn4);
printf("This is executed first.\n");
}
int fn1()
{
printf("next.\n");
return 0;
}
int fn2()
{
printf("executed ");
return 0;
}
int fn3()
{
printf("is ");
return 0;
}
int fn4()
{
printf("This ");
return 0;
}
结果显示均为:
This is executed first.
This is executed next.