How do modern OS's achieve idempotent cleanup functions for process deaths?

时间:2018-05-09 02:51:00

标签: memory process operating-system resource-cleanup

Let's say that I have an OS that implements malloc by storing a list of segments that the process points to in a process control block. I grab my memory from a free list and give it to the process.

If that process dies, I simply remove the reference to the segment from the process control block, and move the segment back to my free list.

Is it possible to create an idempotent function that does this process cleanup? How is it possible to create a function such that it can be called again, regardless of whether it was called many times before or if previous calls died in the middle of executing the cleanup function? It seems to me that you can't execute two move commands atomically.

How do modern OS's implement the magic involved in culling memory from processes that randomly die? How do they implement it so that it's okay for even the process performing the cull to randomly die, or is this a false assumption that I made?

1 个答案:

答案 0 :(得分:1)

我假设你的问题归结为如果该进程崩溃,操作系统如何剔除进程的内存。

尽管我在这些方面受过自我教育,但我会给你两种方法,操作系统可以确保在进程崩溃时回收进程使用的任何内存。

在具有虚拟内存的典型现代CPU和现代操作系统中:

您有两层分配。每当进程调用malloc时,malloc都会尝试满足内核给出进程的已有内存页面的请求。如果没有足够的页面可用,malloc会要求内核分配更多页面。 在这种情况下,每当进程崩溃或者即使它正常退出时,内核也不关心malloc做了什么,或者进程忘记释放什么内存。它只需要释放它为进程提供的所有页面。

在一个更简单的操作系统中,它并不关心性能,内存碎片或虚拟内存,甚至可能不关心内存保护:

Malloc / free完全在内核端实现(例如:系统调用)。每当进程调用malloc / free时,内核都会完成所有工作,因此知道需要释放的所有内存。一旦进程崩溃或退出,内核就可以清理。由于内核永远不应该崩溃,并保留每个进程所有已分配内存的记录,因此它是微不足道的。

就像我说的那样,我受过自我教育,而且我没有检查Linux或Windows如何实现它。