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函数调用的(这里代码没贴上来)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值