iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 10
1
自我挑戰組

30 Days 如何把 C 語言偽裝成高階語言 OWO /系列 第 10

Days 10: atexit()、函數程序結束時調用函數

▌atexit() 函數


▌函數原型:

int atexit(void (*func)(void))

C庫函數 int atexit(void (*func)(void)) 會導致程序終止時被調用指定的函數功能。可以注冊在你喜歡的任何地方,但它會被稱為當時的程序終止的終止函數。

需要 #include <stdlib.h>

可以使用 atexit() 註冊函數,
在程序結束的時,會調用被註冊的函數的,
一个程序中最多可以用 atexit() 註冊32個函數。

atexit() 的參數是一個函數指標
必須是沒有回傳和沒有參數的函數。


▌函數地址:

函數也會具有地址,
函數指標就是它的地址。

例如:

void function(){ /*do somethings*/ }

&function 會是它的函數地址
function 這個名字可以代表它的函數地址。

習慣上,會偏向使用忽略 & 的做法。


▌函數指標:

函數指標是一種具有參數形式的指標

void (*ptr)();
int (*ptr2)();
int (*ptr3)(int, int);

可以指向函數,
進行調用函數的工作。

下面用 atexit() - C語言庫函數 - C語言標準庫 提供的例子:

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

void functionA ()
{
   printf("This is functionA");
}

int main ()
{
   /* register the termination function */
   atexit(functionA );
   
   printf("Starting  main program...");

   printf("Exiting main program...");

   return(0);
}

將產生以下結果:

Starting main program...
Exiting main program...
This is functionA

▌注意:

註冊函數的次序與調用函數的次序相反
即是按照先入後出的模式。


▌有什麼用途?

可以在程序關閉時進行關閉檔案fclose()的動作,
可以進行日誌 log 輸出 ,
還可以進行垃圾回收的動作, (所以之後用到)
總言之是一些善後工作


▌參考資料:

使用 atexit() 讓程式被關閉時做對應的動作 – Heresy's Space
https://kheresy.wordpress.com/2013/11/28/c-atexit/
atexit() - C語言庫函數 - C語言標準庫
http://tw.gitbook.net/c_standard_library/c_function_atexit.html
C 库函数 – atexit() | 菜鸟教程
http://www.runoob.com/cprogramming/c-function-atexit.html
C++中Exit()与atexit()函数的使用 - sruru的专栏 - CSDN博客
https://blog.csdn.net/sruru/article/details/7941117


上一篇
Days 9: 動態記憶體分配:malloc()、calloc()、realloc()、free(),內存洩露
下一篇
Days 11: 什麼是垃圾回收器?
系列文
30 Days 如何把 C 語言偽裝成高階語言 OWO /31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言