在信号处理程序中仅调用异步信号安全函数?

在信号处理程序中仅调用异步信号安全函数?

我是信号和信号处理程序的新手,我正在读一本书,上面写着

在处理程序中仅调用异步信号安全函数。异步信号安全或简单安全的函数具有可以从信号处理程序安全调用的属性,因为它不能被信号处理程序中断。请注意,许多流行的函数(例如 printf、sprintf、malloc 和 exit)并不安全。

我在这里有点困惑,以下是我的问题:

安全函数不能被信号处理程序中断是什么意思?这是否意味着安全函数在开始时在内部阻塞信号并在完成之前解除阻塞信号,以便安全函数不会被其他信号中断?

答案1

当内核向进程传递信号时,它会停止进程的执行(无论进程在何处),注入对信号处理程序函数的调用,然后调度进程,从而使其执行信号处理程序。由于该调用可以注入到任何地方,因此当注入信号处理程序时,您的程序可能正在操作非本地状态。调用依赖于该非本地状态的另一个函数将导致未定义的行为。

任何访问/修改非本地状态的函数通常都不是信号安全的。从man 7 signal-safety

To avoid problems with unsafe functions, there are two possible
choices:

1. Ensure that (a) the signal handler calls only async-signal-safe
   functions, and (b) the signal handler itself is reentrant with
   respect to global variables in the main program.

2. Block signal delivery in the main program when calling functions
   that are unsafe or operating on global data that is also accessed by
   the signal handler.

Generally, the second choice is difficult in programs of any complexity,
so the first choice is taken.

该手册页继续枚举了信号安全函数集。

相关内容