夜雨聆风学习资料网

ARTICLE · 1434193

《深入浅出:C/C++程序退出时的“幕后工作”》

《深入浅出:C/C++程序退出时的“幕后工作”》

往期精选文章

本地部署DeepSeek大模型原来这么简单!

深入探究c++中符号冲突导致的未预期行为

教你学会使用Jenkins

C++性能分析-perf火焰图

AddressSanitizer:C/C++内存问题的终极检测利器

深入理解Linux动态库加载、链接与运行的全过程

深入理解编译器选项 -fpic:位置无关代码的艺术

深入理解glibc中内存分配器malloc底层原理

相关文章

程序诞生记:内核、加载器与运行时如何协作

引言
一个简单的return 0;背后,隐藏着怎样的逻辑?本文将深入探索C/C++程序从main函数返回到完全消失的全过程,揭示用户程序、运行时库和操作系统如何协同完成这场精心编排的"谢幕仪式"。本文以Linux平台进行说明。
代码示例
#include<stdio.h>#include<stdlib.h>intmain(int argc, char** argv){  printf("hello candy!\n");  return 0;}
编译代码
g++ -o main main.cpp
执行程序, 果不其然输出了"hello candy!", 那么程序return 0后发生了什么呢?或者说这里边还隐藏着哪些不为人知的奥秘呢,本来就来深入探索下这里边背后的逻辑。
文章回顾
从程序诞生记:内核、加载器与运行时如何协作这篇文章我们知道了程序是如何启动执行的,这里边经过了操作系统->动态链接器->运行时库->用户程序(main),那么本文会继续按这几个流程来说明程序退出的流程以及底层的一些逻辑。
以下是glibc源码从__libc_start_main函数的片段,用于回顾说明程序是如何进入用户main函数的:
当用户main函数返回后就来到了glibc中的exit函数,那么这个exit函数实现是怎么样的?它做了哪些事情?
__run_exit_handlers的源码如下:
/* Call all functions registered with `atexit' and `on_exit',   in the reverse of the order in which they were registered   perform stdio cleanup, and terminate program execution with STATUS.  */voidattribute_hidden__run_exit_handlers (int status, struct exit_function_list **listp,             bool run_list_atexit, bool run_dtors){  /* The exit should never return, so there is no need to unlock it.  */  __libc_lock_lock_recursive (__exit_lock);  /* First, call the TLS destructors.  */  if (run_dtors)    call_function_static_weak (__call_tls_dtors);  __libc_lock_lock (__exit_funcs_lock);  /* We do it this way to handle recursive calls to exit () made by     the functions registered with `atexit' and `on_exit'. We call     everyone on the list and use the status value in the last     exit (). */  while (true)    {      struct exit_function_list *cur;    restart:      cur = *listp;      if (cur == NULL)    {      /* Exit processing complete.  We will not allow any more         atexit/on_exit registrations.  */      __exit_funcs_done = true;      break;    }      while (cur->idx > 0)    {      struct exit_function *const f = &cur->fns[--cur->idx];      const uint64_t new_exitfn_called = __new_exitfn_called;      switch (f->flavor)        {          void (*atfct) (void);          void (*onfct) (int status, void *arg);          void (*cxafct) (void *arg, int status);          void *arg;        case ef_free:        case ef_us:          break;        case ef_on:          onfct = f->func.on.fn;          arg = f->func.on.arg;          PTR_DEMANGLE (onfct);          /* Unlock the list while we call a foreign function.  */          __libc_lock_unlock (__exit_funcs_lock);          onfct (status, arg);          __libc_lock_lock (__exit_funcs_lock);          break;        case ef_at:          atfct = f->func.at;          PTR_DEMANGLE (atfct);          /* Unlock the list while we call a foreign function.  */          __libc_lock_unlock (__exit_funcs_lock);          atfct ();          __libc_lock_lock (__exit_funcs_lock);          break;        case ef_cxa:          /* To avoid dlclose/exit race calling cxafct twice (BZ 22180),         we must mark this function as ef_free.  */          f->flavor = ef_free;          cxafct = f->func.cxa.fn;          arg = f->func.cxa.arg;          PTR_DEMANGLE (cxafct);          /* Unlock the list while we call a foreign function.  */          __libc_lock_unlock (__exit_funcs_lock);          cxafct (arg, status);          __libc_lock_lock (__exit_funcs_lock);          break;        }      if (__glibc_unlikely (new_exitfn_called != __new_exitfn_called))        /* The last exit function, or another thread, has registered           more exit functions.  Start the loop over.  */        goto restart;    }      *listp = cur->next;      if (*listp != NULL)    /* Don't free the last element in the chain, this is the statically       allocate element.  */    free (cur);    }  __libc_lock_unlock (__exit_funcs_lock);  if (run_list_atexit)    call_function_static_weak (_IO_cleanup);  _exit (status);}
接下来在分析源码之前我们先用gdb调试这一过程:
1. 用户程序main函数return 0; 接着来到了exit(对应__GI_exit)函数。
2. 接着进入了__run_exit_handlers函数,执行线程局部存储(tls)的析构函数(释放资源)
注:这个析构函数的注册时机分几种情况,通常是在tls变量被初始化的时候。对于动态tls(使用dlopen加载的库),在库初始化函数中注册。对于静态tls,在程序启动时,主线程的tls初始化期间注册,而每个线程在创建时也会初始化自己的tls并注册相应的析构函数。对应的glibc线程tls析构函数源码如下所示:
所以当线程退出时,就会自动去遍历这个链表,依次执行对应tls对象或实例的析构函数,注意这个执行顺序是先进后出的,符合C++里对象的构造/释放顺序。
这里可以通过使用全局/静态对象|实例来举例说明,代码如下
#include<stdio.h>#include<stdlib.h>class Test {public:    Test() : a(0) {}    voidsetVar(int val){ a = val; }    intgetVar()const{ return a; }private:    int a;};static Test g_inst;intmain(int argc, char** argv){  printf("hello candy!\n");  return 0;}
调试汇编所示:
程序启动时:
执行流程 :运行时函数_start -> __libc_start_main(glibc)-> GLOBAL_sub_I_main -> 其它一些初始化  -> 用户main函数
该图表示的是在程序启动之前调用"Z41__static initialization_and destruction_0ii"执行全局或者静态对象|实例的初始化,并且也会将对应的反初始化(析构函数)注册给glibc。
此时调试发现全局对象已如期构造。
3. 接下来就会执行一系列退出函数(exit),这些退出函数包括以下几种类型:
ef_on - 通过on_exit()注册的函数
使用场景: 这个类型的退出函数可以传递状态和自定义参数,所以在某些情况下,我们希望在退出时执行一些依赖于退出状态或特定参数的清理工作。例如,一个库可能希望根据程序是否正常退出(状态码为0)来执行不同的清理操作, 具体使用需要结合程序。
ef_at - 通过atexit()注册的函数
使用场景:它常用于资源清理(关闭打开的文件、释放动态分配的内存)、状态同步等操作。
ef_cxa - 通过__cxa_atexit()注册的C++析构函数
使用场景:这主要是为了支持C++的静态对象的析构,以及动态库的卸载清理。
接下来执行glibc的最后一个清理动作  -> 清理io缓冲区
这两个函数做的工作也相对单纯,主要是做以下两个事情:

_IO_flush_all:刷新所有文件流(即写入所有缓冲的数据)。

_IO_unbuffer_all:取消所有文件流的缓冲(即释放缓冲区,并将文件流设置为无缓冲)。

最后通过系统调用_exit告知系统程序退出,接着系统执行剩余的一些资源释放等相关的动作。至此,程序return的流程执行完毕!

回首页,搜索你想要的文档

在首页搜索框输入关键词,快速定位资料

文库首页搜索指引 立即搜索

相关学习资料