Mohammad_mhh
Mohammad_mhh

Reputation: 45

Shared library in C with two application

In case of a shared library between two applications, does each application use it's own copy of the library during run time ? If they use the same instance of the library, what happens to the global variables inside the library ?

Upvotes: 3

Views: 2342

Answers (3)

Marco Guerri
Marco Guerri

Reputation: 942

For Unix-like operating systems, when you first execute your applications, the page tables of the two processes which map the library address space will point to the same frames in memory where the library is loaded.

However, the page tables which map the data section of the library are handled with Copy on Write mechanism. As soon as you try to write a global variable, the OS will create a process specific copy of the page containing the variable and will remap the page table of the process accordingly.

Upvotes: 2

user4098326
user4098326

Reputation: 1742

It depends on the operating system. On most Unix-like systems, shared libraries use position-independent code, so the memory used by the code segment(which holds instructions and read-only variables) can be shared between processes, but each process still has its own data segment(which holds other variables).

Upvotes: 3

rost0031
rost0031

Reputation: 1926

Each program creates a new instance of the library in its own memory space. They are not shared and the 2 programs will not see each other's data.

Take a look at how dynamic libraries are loaded: http://eli.thegreenplace.net/2011/08/25/load-time-relocation-of-shared-libraries

The same is true for statically linked libraries except instead of being loaded at runtime, they are linked at compile time.

Upvotes: 0

Related Questions