如何将内存从进程返回到OS [英] How to return memory from process to the OS

查看:104
本文介绍了如何将内存从进程返回到OS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在各种操作系统中的内存管理都有问题.

I have an issue with memory management in various operating systems.

我的程序是一台服务器,它进行一些处理可能会占用几GB的内存.之后,它会释放大部分内存,并等待几个小时,直到另一个请求到达.

My program is a server that does some processing that could take a few GB of memory. After that, it releases most of the memory while it waits for a few hours until another request arrives.

在AIX和Solaris上,我观察到以下行为,

On AIX and Solaris, I observe the following behavior,

释放内存时,内存不会返回给操作系统.进程使用的虚拟内存量始终增加-从不减少.物理内存达到上限也是如此.因此看来,我们在睡眠模式下也使用了所有这些内存.

When I free memory, the memory is not returned back to the operating system. The amount of virtual memory used by a process always increases - never decreases. The same is true for the physical memory, up to its limit. Thus it appears that we use all this memory in sleep mode as well.

何时可以将该内存返回给OS?我该怎么做?

When this memory can be returned back to OS? How can I make it?

Linux是不同的:看起来有时候确实会返回内存,但是我无法理解何时何地.例如,我有一个场景,其中一个请求之前的进程是100MB,然后在高峰时是700MB,而在释放所有进程之后,它下降到600MB.我不明白-如果Linux将内存还给操作系统,那为什么不全部呢?

Linux is different: it appears that is does return memory sometimes, but I'm not able to understand when and how. I have for example a scenario in which the process before a request was 100MB, then 700MB at the peak, and after releasing all that it was down to 600MB. I don't understand it - if Linux gives back memory to the OS, why not all of it?

推荐答案

glibc库(通常在Linux中用作标准C库)可以两种方式分配内存-sbrk()或mmap().它将使用mmap()进行足够大的分配.

The glibc library (which is normally used as the standard C library in Linux) can allocate memory in two ways - with sbrk() or with mmap(). It will use mmap() for large enough allocations.

用sbrk()分配的内存不能轻易地再次放弃(仅在特殊情况下,据我所知glibc甚至没有尝试).可以使用munmap()返回使用mmap()分配的内存.

Memory allocated with sbrk() cannot easily be given up again (only in special cases, and as far as I know glibc doesn't even try). Memory allocated with mmap() can be returned using munmap().

如果您希望能够将内存返回给操作系统,则可以直接使用mmap()代替malloc();但是,如果您分配许多小块,这将变得效率低下.您可能需要在mmap()之上实现自己的池分配器.

If you depend on being able to return memory to the OS, you can use mmap() directly instead of malloc(); but this will become inefficient if you allocate lots of small blocks. You may need to implement your own pool allocator on top of mmap().

这篇关于如何将内存从进程返回到OS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆