CONTENTS | INDEX | PREV | NEXT
atexit
NAME
atexit - specify routine that is automatically called on exit.
SYNOPSIS
#include <stdio.h>
#include <stdlib.h>
int error = atexit(funcptr);
void (*funcptr)(void);
FUNCTION
The atexit() routine adds a function to the list of functions called
when the program exits. The atexit() routine is called before
stdio and fd's are closed down. This exit function is called whenever
the program exits, even if main() just returns an exit code.
atexit() will return 0 on success, -1 on failure. Some systems limit
the number of atexit() functions one can add (DICE does not) so if
you add more than one you should check the return value.
EXAMPLE
/*
* atexit() is useful to free up resources that would otherwise not
* be freed up by DICE. For example, anything AllocMem()d. The
* atexit() function is called on any exit ... return from main,
* call to exit, or ^C.
*
* normally your atexit routine cannot make assumptions as to what
* has been allocated and what has not since exit() can be called
* from anywhere in the program.. things might not have been allocated
* yet, for example.
*/
#include <stdio.h>
#include <stdlib.h>
extern void *AllocMem();
void *MemPtr;
long MemLen;
void
myexit(void)
{
if (MemPtr) /* only if it is allocated */
FreeMem(MemPtr, MemLen);
MemPtr = NULL;
}
/*
* here we can take a ^C anywhere... before we allocate, after, or
* even after we free (note I am careful to set MemPtr back to NULL!
*/
main()
{
short i;
atexit(myexit);
for (i = 0; i < 100; ++i)
printf("Before Alloc %dn", i);
MemLen = 32;
MemPtr = AllocMem(MemLen, 0);
if (MemPtr == NULL) {
puts("uh oh, AllocMem failed!");
exit(1);
}
for (i = 0; i < 100; ++i)
printf("After Alloc %dn", i);
FreeMem(MemPtr, MemLen);
MemPtr = NULL; /* must do this or atexit routine thinks */
/* memory is still allocated! */
for (i = 0; i < 100; ++i)
printf("After Free %dn", i);
return(0);
}
1> avail
1> testprg
... (you can ^C the testprg at any point)
1> avail (no memory loss should be seen)
INPUTS
void (*funcptr)(void); routine to add to exit call list, takes
no arguments and returns nothing.
RESULTS
int error; 0 on success, -1 on failure.
SEE ALSO
onbreak