[comp.lang.c] atexit

hendrik@zeusa.UUCP (Hendrik Vermooten) (04/28/90)

I did write my own atexit() routines a while ago. Here is most of the
(important) code. The only snag is that you have to call sysexit() instead
of exit(), and you mustn't let your main() just "fall out" the bottom
brace; you *must* call sysexit() if you want your functions to execute.

---------------------------------------------------------------------------

#define MAX_FUNCTIONS  32 /* Same as ANSI limit */

typedef struct {
                 int (*func_ptr) ();
               } func_struct;

static func_struct function [MAX_FUNCTIONS];
static unsigned    no_atfunctions = 0;

int atexit (func_ptr)
  int (*func_ptr) ();
{
  if (no_atfunctions < MAX_FUNCTIONS)
  {
    function [no_atfunctions].func_ptr = func_ptr;
    ++no_atfunctions;
    return (0);
  }
  else
  {
    message ("Programmer attempted too many (%u) atexit assignments",
             no_atfunctions);
    return (no_atfunctions);
  }
}

static void run_exit ()
{
  unsigned  i;

  for (i = no_atfunctions; i > 0; i--)
    (*(function [i-1].func_ptr)) ();
}

void sysexit (errorlevel, format, va_alist)
  int  errorlevel;
  char *format;
  va_dcl
{
  va_list  argptr;
  char     errormsg [255];

  va_start (argptr);

  if (errorlevel > 0)
  {
    vsprintf (errormsg, format, argptr);
    fprintf (stderr, "%s\n", errormsg);
    va_end (argptr);
  }
  run_exit ();
  exit (errorlevel);
}

---------------------------------------------------------------
Hendrik Vermooten, ZEUS software
Bang: ..!uunet!ddsw1!olsa99!zeusa!hendrik or hendrik@zeusa.UUCP
---------------------------------------------------------------