Shared Library Memory Model-- How does it work?

Status
Not open for further replies.
When compiling a C program, there is an option to compile common code segment into a shared library.

But I don't quite understand how shared library works.
Does it exists in its own process or the caller's process?
When a process calls the shared library, does it load a new copy of the library or it uses the same one?

Can someone help me understand the concept?
 

Midlands

Ars Praetorian
535
Subscriptor
Shared libraries are a grey area. They exist in virtual memory, and are mapped repeatedly into each caller's address space -- but it's just a mapping, so only one copy of the code and data (static data, not dynamically-allocated memory) exists at any given time. Since this code and data is typically read-only, this is not a problem.

I don't remember whether shared, writeable data is copy-on-write (and therefore a separate copy for each process) or a single copy (and therefore actually-shared data). Perhaps it depends on the OS.

The kernel will usually reference-count the library such that when the last process that uses it is freed, the library is freed. For very-commonly-used libraries (like libc on a UN*X system), this means the library is always loaded.
 
Status
Not open for further replies.