Can I use fprintf(stderr)
in a signal (SIGALRM) handler with glibc/linux?
No you cannot. Check the manpage signal(7) for a list of async-signal-safe functions. fprintf
is not included in that list.
If you don't need formatting then you can use write(STDERR_FILENO, <buf>, <buflen>)
to write to stderr.
This is not safe, quoting IBM DeveloperWorks article about Signal Handling Safety
Suppose the signal handler prints a message with fprintf and the program was in the middle of an fprintf call using the same stream when the signal was delivered. Both the signal handler's message and the program's data could be corrupted, because both calls operate on the same data structure: the stream itself.
来源:https://stackoverflow.com/questions/4554129/linux-glibc-can-i-use-fprintf-in-signal-handler