return、exit、_exit和atexit的化学作用?

文字记录

这节课学了一点关于return、exit、_exit和atexit的关系。
从man手册里面看到atexit是一个库函数。

DESCRIPTION
The atexit() function registers the given function to be called at
normal process termination, either via exit(3) or via return from the
program’s main(). Functions so registered are called in the reverse
order of their registration; no arguments are passed.

大概意思是atexit是会在函数结束之前会调用一个已经注册了的函数。最后还有一点写到,那些注册了的函数是按照反着的顺序被调用的,就像栈一样,先进后出。

实现代码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>


void function1(void)
{
	printf("the test of atexit\n");

}
void function2(void);

int main(int argc,char* argv[])
{
	if (2 != argc)
	{
		printf("usage: ./a.out password\n");
		return -1;
	}
	printf("test 1\n");

	atexit(&function1);
	atexit(&function2);
	
	printf("test 2\n");

	//exit(0);
	//_exit(0);
	
	return 0;
}

void function2(void)
{
	printf("the test2 of atexit\n");

}

解析

1.两个atexit在两个printf之间,说明atexit是真的在程序最后才运行的。
2.我的atexit是先1再2的,但是结果是先test2再test出现,所以验证了先进后出的这个结果。
3.下面的截图是return 0 接的atexit,是可以执行的,同样如果用exit(0)的话也可以执行atexit,但是用_exit的话就不会执行atexit,而是直接结束了。
在这里插入图片描述
4.atexit不仅仅只能用在main函数里面的,怎么说呢,就是在其他函数里面用也行,我后面测试的时候把atexit加在了function1里面,用atexit调用function2也行,反正都是会被main函数调用的(这里代码没贴上来)。

发布了38 篇原创文章 · 获赞 1 · 访问量 1041

猜你喜欢

转载自blog.csdn.net/qq_40897531/article/details/103753605