Calling a standard library function in signal hand

2019-06-21 06:10发布

问题:

Why is calling a standard library function inside a signal handler discouraged?

回答1:

This is explained in the GNU LibC documentation.

If you call a function in the handler, make sure it is reentrant with respect to signals, or else make sure that the signal cannot interrupt a call to a related function.

And just in case, here's the Wikipedia page on reentrant functions.

A computer program or routine is described as reentrant if it can be safely called again before its previous invocation has been completed (i.e it can be safely executed concurrently).



回答2:

Its not only re-entrancy issues, depending on the signal being services you also want to avoid inadvertent calls to malloc() (i.e. asprintf()) and other variadic expansion (i.e. printf()).



回答3:

It is all running fine and stuff, until you run into some mysterious bugs which are totally untraceable :)

man 7 signal will give you a list of system calls which are safe to call from a signal handler. It is described in POSIX as well.



回答4:

Because the library function may not be reentrant.



标签: c unix gcc signals