how is a shared library file called by two different processes in Linux?
In Linux, I have a shared library file called foo.so When I execute 2 different process p1, p2 that both use foo.so. Doe开发者_运维问答s this foo.so get overlapped by those 2 process?
On Unix-based systems (includes Linux), the code segment (.text) may be shared among multiple processes because it's immutable. Is this overlapping you mention?
Basically, each shared library that contains static data (such as global variables) has a Global Offset Table (GOT). On shared libraries, all references to static data (think of global vars) occur via GOT (they're indirect). So even if the code segment is shared among multiple processes, each process has its exclusive mapping of other segments of the shared library, including the respective GOT, whose entries are relocated accordingly.
In short, only code is shared among processes, not data. However, I think constants may be an exception depending on compilation flags.
I also recommend chapter 10, Dynamic Linking and Loading, from the following book: Linkers and Loaders.
The code for the shared library is copied (or more accurately, mapped) into memory by the operating system.
Then the OS gives each of the processes access to that one copy in memory.
It's possible that each of the processes will "see" the copy as being at a different memory address than the other. This is resolved by the CPU's memory management unit.
It can get more complicated than this, but that's basically how things work in Linux and other Unix-related operating systems like Mac OS X.
The two processes are using the same physical address of the code segment of the shared library, but their virtual address is different for the two processes. Virtual memory is helping as implementing this feature here.
According to the book, Computer Systems: A Programmer's Perspective, in chapter 9.5 VM as a tool for Memory Management
However, in some instances it is desirable for processes to share code and data. For example, every process must call the same operating system kernel code, and every C program makes calls to routines in the standard C library such as printf. Rather than including separate copies of the kernel and standard C library in each process, the operating system can arrange for multiple processes to share a single copy of this code by mapping the appropriate virtual pages in different processes to the same physical pages.
精彩评论