[issue1195571] simple callback system for Py_FatalError

STINNER Victor report at bugs.python.org
Wed Jun 8 23:33:32 CEST 2011


STINNER Victor <victor.stinner at haypocalc.com> added the comment:

fatalhook-2.patch: I don't understand the documentation. It says "Cause :cfunc:`Py_FatalError` to invoke the given function instead of printing to standard error and aborting out of the process.", but if the callback does nothing, the message+traceback is printed.

If the "fatal hook" is supposed to replace the function displaying the message, you should move the code displaying message+traceback in a subfunction and use it as the default hook function.

Pseudo code:
---------------
static fatal_error(const char *msg)
{
   printf("Fatal error: %s\n", msg);
   ... print traceback ...
}

static PyFatalHook fatalhook_func = fatal_error;

void
Py_FatalError(const char *msg)
{
    if (fatalhook_func != NULL)
       fatalhook_func(msg);
    ... windows debugger code ...
    abort();
}
---------------

NULL is a special hook value: don't print message+traceback, but exit (call abort()).

The hook can exit the process using something else than abort(). But if the hook doesn't exit, the default exit code is executed (call abort()), but the "Fatal error..."+traceback is not printed.

> fatalhook_func != Py_FatalError

I think that this test is just overkill, or it should be moved to Py_SetFatalHook (e.g. set the hook to NULL if Py_FatalError is passed).

> I also made Py_SetFatalHook() return the previous hook; 
> it could be useful to set a function temporarily,
> even if this is not thread safe.

The previous hook can also be used to chain hooks. For example, if you would like to display the traceback but also do a special thing before exit, you can do something like:
------------------
void init()
{
   previous = Py_SetFatalHook(my_hook)
}

void my_hook(const char *msg)
{
  ... cleanup ...
  previous(msg);
}
------------------

About thread safety: because Py_FatalError() is called in the worst case (when something really bad happens), I think that it is better to not use something related to thread to avoid issues like deadlocks, and keep the code simple.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue1195571>
_______________________________________


More information about the Python-bugs-list mailing list