Since printf
is not reentrant, it's not supposed to be safe to use it in a signal handler. But I've seen lots of example codes that uses printf
this way.
So my question is: when do we need to avoid using printf
in a signal handler, and is there a recommended replacement?
Implement your own async-signal-safe
snprintf("%d
and usewrite
It is not as bad as I thought, How to convert an int to string in C? has several implementations.
Since there are only two interesting types of data that signal handlers can access:
sig_atomic_t
globalsint
signal argumentthis basically covers all interesting use cases.
The fact that
strcpy
is also signal safe makes things even better.The POSIX program below prints to stdout the number of times it received SIGINT so far, which you can trigger with
Ctrl + C
, and the and signal ID.You can exit the program with
Ctrl + \
(SIGQUIT).main.c:
Compile and run:
After pressing Ctrl + C fifteen times, the terminal shows:
where
2
is the signal number forSIGINT
.Tested on Ubuntu 18.04. GitHub upstream.