Python 中调用堆栈的内核可见性
Kernel visibility into the call stack in Python
OS 是否可以查看 CPython 中的调用堆栈(例如函数之间的调用)?例如。 OS 以何种方式参与 Python 堆栈的创建、检索 and/or 管理及其 stack frames 的操作?
上下文:
- 我的理解是Python解释器不支持尾调用递归,所以这似乎是留给Python处理的事情。
- 大多数 OS 对堆栈大小施加最大限制(例如,我相信 Linux OS 最大堆栈大小默认为 8192 KB,但可以更改通过例如
ulimit
),这意味着内核显然可以参与至少限制调用堆栈的大小。
In what way is the OS involved in the creation, retrieval and/or management of the Python stack and operations of its stack frames?
不是。堆栈帧供进程处理,内核不会干涉。
My understanding is that the Python interpreter does not support tail call recursion, so this seems to be something left to Python to handle.
嗯,是的,Python 的工作是处理自己的堆栈,而不考虑尾递归。 Python 不支持尾递归的事实可能对深度递归调用有一些缺点,但代码总是可以重写为迭代。
另请参阅:What is the maximum recursion depth in Python, and how to increase it?
the kernel clearly can get involved in at least limiting the size of the call stack
是的,确实内核确实限制了堆栈大小。它的实现方式是在栈顶之后分配一个不可见的保护页:当堆栈已满时,进行另一个调用(从而添加另一个堆栈帧)将触发读取 and/or 写入保护页,内核会检测到它并增加堆栈大小。不过,这种情况只会发生 达到某个预定义的数量 ,此后进程会因超过允许的最大堆栈大小而被终止。
另请参阅:Stack memory management in Linux
OS 是否可以查看 CPython 中的调用堆栈(例如函数之间的调用)?例如。 OS 以何种方式参与 Python 堆栈的创建、检索 and/or 管理及其 stack frames 的操作?
上下文:
- 我的理解是Python解释器不支持尾调用递归,所以这似乎是留给Python处理的事情。
- 大多数 OS 对堆栈大小施加最大限制(例如,我相信 Linux OS 最大堆栈大小默认为 8192 KB,但可以更改通过例如
ulimit
),这意味着内核显然可以参与至少限制调用堆栈的大小。
In what way is the OS involved in the creation, retrieval and/or management of the Python stack and operations of its stack frames?
不是。堆栈帧供进程处理,内核不会干涉。
My understanding is that the Python interpreter does not support tail call recursion, so this seems to be something left to Python to handle.
嗯,是的,Python 的工作是处理自己的堆栈,而不考虑尾递归。 Python 不支持尾递归的事实可能对深度递归调用有一些缺点,但代码总是可以重写为迭代。
另请参阅:What is the maximum recursion depth in Python, and how to increase it?
the kernel clearly can get involved in at least limiting the size of the call stack
是的,确实内核确实限制了堆栈大小。它的实现方式是在栈顶之后分配一个不可见的保护页:当堆栈已满时,进行另一个调用(从而添加另一个堆栈帧)将触发读取 and/or 写入保护页,内核会检测到它并增加堆栈大小。不过,这种情况只会发生 达到某个预定义的数量 ,此后进程会因超过允许的最大堆栈大小而被终止。
另请参阅:Stack memory management in Linux