Contents
  1. 1. 进程终止
  2. 2. 退出函数
  3. 3. atexit 函数
  4. 4. iOS 上的应用

进程终止

有 8 种方式使进程终止,其中五种是正常终止:

  1. 从 main 中返回
  2. 调用 exit
  3. 调用 _exit 或者 _Exit
  4. 最后一个线程从其启动例程中返回
  5. 从最后一个线程调用 pthread_exit

异常终止的方式有三种:

  1. 调用 abort
  2. 接收到一个信号
  3. 最后一个线程对取消请求做出响应

启动例程调用 main 函数大概是

exit(main(argc, argv))

退出函数

#include <stdlib.h>
void exit(int status)
void _Exit(int status)

#include <unistd.h>
void _exit(int status)

exit 函数在退出的时候会统一清理并关闭 IO 流,对所有打开的流进行 fclose 操作。这样一来输出缓冲中的数据都会写到文件上。重定向 stdout 随后恢复——探究 printf里也有提及。

main 函数中 return 一个整型值跟用这个整型值调用 exit 效果是一样的。

atexit 函数

一个进程可以注册最多 32 个函数,这些函数被 exit 自动调用。atexit 注册的函数被执行的顺序跟注册的顺序是反过来的,注册多次调用多次。
main 函数退出之时做一些诸如关闭所有文件流清理工作,以及运行 atexit 注册的函数。

iOS 上的应用

exit 退出时,applicationWillTerminate 并不会调用。也许可以用来做一些特定的清理工作,并没有想到特别好的应用场景。
关于多线程这块儿

dispatch_async(dispatch_get_global_queue(0, 0), ^{
   exit(0);
});

如果在 atexit 注册的函数中执行一个同步阻塞的工作比如 sleep(10),主线程依旧能响应。

I am test
Main thread is still available
Main thread is still available
Main thread is still available
Main thread is still available
Main thread is still available
exit test method
Contents
  1. 1. 进程终止
  2. 2. 退出函数
  3. 3. atexit 函数
  4. 4. iOS 上的应用