Reputation: 84551
Out of curiosity I am trying to get the libc on_exit function to work, but I have run into a problem with a segmentation fault. The difficulty I am having is finding an explanation of the proper use of this function. The function is defined in glibc as:
Function: int on_exit (void (*function)(int status, void *arg), void *arg) This function is a somewhat more powerful variant of atexit. It accepts two arguments, a function and an arbitrary pointer arg. At normal program termination, the function is called with two arguments: the status value passed to exit, and the arg.
I created a small test, and I cannot find where the segmentation fault is generated:
#include <stdio.h>
#include <stdlib.h>
void *
exitfn (int stat, void *arg) {
printf ("exitfn has been run with status %d and *arg %s\n", stat, (char *)arg);
return NULL;
}
int
main (void)
{
static char *somearg="exit_argument";
int exit_status = 1;
on_exit (exitfn (exit_status, somearg), somearg);
exit (EXIT_SUCCESS);
}
Compiled with: gcc -Wall -o fn_on_exit fnc-on_exit.c
The result is:
$ ./fn_on_exit exitfn has been run with status 1 and *arg exit_argument Segmentation fault
Admittedly, this is probably readily apparent for seasoned coders, but I am not seeing it. What is the proper setup for use of the on_exit function and why in this case is a segmentation fault generated?
Upvotes: 0
Views: 744
Reputation: 59997
The line of code
on_exit (exitfn (exit_status, somearg), somearg);
Should be
on_exit (exitfn, somearg);
As you do not want to call the exitfn
at this stage (that returns NULL!)
Upvotes: 4