shared libraries and memory

James Wilkinson fedora at westexe.demon.co.uk
Tue Jul 11 12:22:09 UTC 2006


Mike - EMAIL IGNORED wrote:
> When I use a shared library, is it all in memory,
> or is only the object code currently in use in
> memory?  I ask because I have some object code
> that will be used only rarely.

Look up "demand paging" for details of how it gets *into* memory (the
short answer is "it depends: Linux won't necessarily load all of a large
library, but might well load all of a small one").

See below for how it gets *out* of memory.

> Additionally, when the exe using the function exits and
> no other exe is using it, is the memory freed?

That's not how modern operating systems work.

The same physical memory will be regarded *both* as the copy of the
library which is actually executed (by any program that needs it) *and*
as a cache of what's on disk. If all the programs using the library
terminate, then the memory is regarded simply as a cache, in case the
library is needed again in the near future.

This *is* a Good Thing, because at that point in time, the system has no
better use for the memory. Completely free memory isn't earning its
keep.

The system *does* keep a small pool of really free memory (so new
programs, new requests for memory, or new data loaded from disk has
somewhere to go). When this pool gets small, the kernel will attempt to
free more memory by finding a 4K memory page that hasn't been used
recently, and either "swapping" it out to disk, or (in the case of a
library) noting that there's a copy on disk anyway, and discarding the
memory page. If it needs the data again, it will read it back in.

The important thing to note is that normally, the kernel will look at
(almost) all memory, whether it's just cache, whether programs are
running out of it, or whether it's working data. This happens
automatically, and without special privileges, a program can't stop it
happening.

Basically, the kernel worries about this on your behalf, so you don't
have to.

More reading:
http://lwn.net/Articles/147879/
http://lwn.net/Articles/83588/

James.
-- 
E-mail address: james | A: Because people don't normally read bottom to top.
@westexe.demon.co.uk  | Q: Why is top-posting such a bad thing?
                      | A: Top-posting.
                      | Q: What is the most annoying thing in e-mail?




More information about the fedora-list mailing list