python 中的错误分同步异步吗?

python 中的错误分同步异步吗?

最近在研究信号机制,看到 python 官网 https://docs.python.org/zh-cn/3/library/signal.html?highlight=signal#execution-of-python-signal-handlers 中信号处理的描述如下:

捕获同步错误是没有意义的,例如 SIGFPE 或 SIGSEGV ,它们是由 C 代码中的无效操作引起的。Python 将从信号处理程序返回到 C 代码,这可能会再次引发相同的信号,导致 Python 显然的挂起。 从Python 3.3开始,你可以使用 faulthandler 模块来报告同步错误。

这里提到了一个概念 :同步错误,那什么是异步错误呢?

Linux常见信号大全


回答:

参考

  • https://stackoverflow.com/que...
  • https://www.linuxjournal.com/...
  • IEEE Std 1003.1-2017 (Revision of IEEE Std 1003.1-2008)
  • https://man7.org/linux/man-pa...
  • https://www.linuxjournal.com/...
  • ftp://ftp.gnu.org/old-gnu/Manuals/glibc-2.2.3/html_chapter/libc_24.html

原文 synchronous error 确实有点怪,不过从上下文看其实说的是信号signal而不是错误error

在这个前提下翻了下 stackoverflow。确切地说,同步和异步指的是信号在何处产生。在当前执行的指令流里产生的信号被叫做同步信号,从外部产生并递送进来的叫异步信号。

在上面 glibc 手册里说的比较清楚:

Signals may be generated synchronously or asynchronously. A synchronous signal pertains to a specific action in the program, and is delivered (unless blocked) during that action. Most errors generate signals synchronously, and so do explicit requests by a process to generate a signal for that same process. On some machines, certain kinds of hardware errors (usually floating-point exceptions) are not reported completely synchronously, but may arrive a few instructions later.

Asynchronous signals are generated by events outside the control of the process that receives them. These signals arrive at unpredictable times during execution. External events generate signals asynchronously, and so do explicit requests that apply to some other process.

A given type of signal is either typically synchronous or typically asynchronous. For example, signals for errors are typically synchronous because errors generate signals synchronously. But any type of signal can be generated synchronously or asynchronously with an explicit request.

linuxjournal 的链接对信号处理说得还是挺好的,也建议读一读。


说了信号再说为什么说处理同步信号没有意义。在上面的 1003.1-2017 文档里其实有提过一嘴:

The behavior of a process is undefined after it returns normally from a signal-catching function for a SIGBUS, SIGFPE, SIGILL, or SIGSEGV signal that was not generated by kill(), sigqueue(), or raise().

大意就是:不是 killsigqueueraise 产生的sigbussigfpesigillsigsegv信号,从信号处理函数返回后的行为是未定义的。

而 glibc 文档中,sigign 文档也有说:

You can ignore program error signals like SIGSEGV, but ignoring the error won't enable the program to continue executing meaningfully.

pythonsignal 包文档也说了:

Python 信号处理程序不会在低级( C )信号处理程序中执行。相反,低级信号处理程序设置一个标志,告诉 virtual machine 稍后执行相应的 Python 信号处理程序(例如在下一个 bytecode 指令)。

因为信号处理程序本身是有个可重入性要求的(async-signal-safety(7)),能在信号处理函数里安全调用的函数很少。加上上面提到的某些信号返回后行为是未定义的,再加上有些错误信号代表的错误并不会因为你忽略了信号就能恢复正常运行(比如 SIGILLSIGSEGVSIGBUS),所以粗略地说,这些信号并不是 python 的信号处理函数能处理的(即便能也没有意义,因为信号代表的故障并没有解决,问题可能来自解释器本身或C扩展)。

以上是 python 中的错误分同步异步吗? 的全部内容, 来源链接: utcz.com/p/938075.html

回到顶部