00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032 #include <stdlib.h>
00033
00034
00035 void exit(int) __attribute__((noreturn));
00036 void _exit(int) __attribute__((noreturn));
00037 void _cleanup(void);
00038
00039
00040 #define FNS_PER_BLOCK 32
00041
00042 struct atexit_fn_block
00043 {
00044 struct atexit_fn_block *next;
00045 void (*fns[FNS_PER_BLOCK])(void);
00046 short used;
00047 };
00048
00049
00050
00051 static struct atexit_fn_block atexit_fns;
00052 static struct atexit_fn_block *current_block = &atexit_fns;
00053
00054
00055 int atexit(void (*fn)(void))
00056 {
00057 if (current_block->used >= FNS_PER_BLOCK)
00058 {
00059 struct atexit_fn_block *new_block =
00060 (struct atexit_fn_block *)malloc(sizeof(struct atexit_fn_block));
00061 if (new_block == NULL)
00062 return -1;
00063
00064 new_block->used = 0;
00065 new_block->next = current_block;
00066 current_block = new_block;
00067 }
00068
00069 current_block->fns[current_block->used++] = fn;
00070
00071 return 0;
00072 }
00073
00074
00075 void exit(int status)
00076 {
00077 struct atexit_fn_block *block = current_block, *old_block;
00078 short i;
00079
00080 while (1)
00081 {
00082 for (i = block->used; --i >= 0 ;)
00083 (*block->fns[i])();
00084 if (block == &atexit_fns)
00085 break;
00086
00087
00088 old_block = block;
00089 block = block->next;
00090 free(old_block);
00091 }
00092
00093 _exit(status);
00094 }