I am just figuring out whether I can call a non-async-safe function in a signal handler.
Quotes from Linux man page signal(7):
If a signal interrupts the execution of an unsafe function, and handler calls an unsafe function, then the behavior of the program is undefined.
and TLPI :
SUSv3 notes that all functions not listed in Table 21-1 (list of async-safe functions) are considered to be unsafe with respect to signals, but points out that a function is unsafe only when invocation of a signal handler interrupts the execution of an unsafe function, and the handler itself also calls an unsafe function.
My interpretation of above quotes is that it's safe to call a non-async-safe function from a signal handler only if the signal handler did not interrupt a non-async-safe function.
For example I install a handler for SIGINT which calls an unsafe function suppose to be crypt(3)
which is non-reentrant namely unsafe.
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sa.sa_handler = handler;
sigaction(SIGINT, &sa, NULL);
And I also call printf()
in an infinite loop in main()
, and I only have the main thread running.
The question is for this simple example, I don't see any bad things happen when the handler interrupted the execution of printf()
and it calls an unsafe function. AFAK, printf()
will acquire a console lock and has an internal buffer to perform buffered I/O, but its state is consistent in this example. And although crypt()
returns a statically allocated string, but it doesn't shared with other function or threads.
Am I misunderstanding something? I want someone to clarify me that is it always unsafe to have a signal handler interrupted the execution of an unsafe function in main program and itself also calls an unsafe function or it is safe to do so in some situation (e.g the simple example above)?
backtrace
command in gdb that will print the call stack, and it will be called from a SIGSEGV handler. It's a OS course project. – Janijania