3.15 プログラムの終了時に常に特定の処理をする
atexit() 関数を使うと、プログラム終了時に指定した関数を実行できる。次の例では終了時に関数 fn() が実行される。 なお、このソース内で tanh() という関数を使っているので、ビルド時に gcc の最後に -lm を付けないとリンクエラーになる。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* 終了時にコールされる関数 */
void fn(void) {
puts("fn called");
}
void main() {
puts("atexit test");
atexit(fn); // fn() atexit() で登録する。
double x = -3.0;
double y;
while (x <= 3.0) {
y = tanh(x);
printf("x=%3.1lf, y=%5.3lf\n", x, y);
x += 0.5;
}
}
実行例
$ ./bin/atexit atexit test x=-3.0, y=-0.995 x=-2.5, y=-0.987 x=-2.0, y=-0.964 x=-1.5, y=-0.905 x=-1.0, y=-0.762 x=-0.5, y=-0.462 x=0.0, y=0.000 x=0.5, y=0.462 x=1.0, y=0.762 x=1.5, y=0.905 x=2.0, y=0.964 x=2.5, y=0.987 x=3.0, y=0.995 fn called $
atexit() はプログラムが正常終了したときのみ実行される。したがって、abort() 関数で異常終了させると実行されない。 一方、exit(EXIT_FAILURE) で終了した場合は、異常終了とみなされない。