Are .text sections shared between loaded ELF executables

dynamic-loadingelfexecutablekernelvirtual-memory

If one program, for example grep, is curretly running, and a user executes another instance, do the two instances share the read-only .text sections between them to save memory? Would the sharing of the main executable text sharing be done similarly to shared libraries?

Is this behavior exhibited in Linux? If so, do other Unices do so as well?

If this is not done in Linux, would any benefit come from implementing executables that often run multiple instances in parallel as shared libraries, with the invoked executable simply calling a main function in the library?

Best Answer

Unix shares executables, and shared libraries are called shared (duh...) because their in-memory images are shared between all users.

I.e., if I run two instances of bash(1), and in one of them run, say, vim(1), I'll have one copy each of the bash and the vim executables in memory, and (as both programs use the C library) one copy of libc.

But even better: Linux pages from the disk copies of the above executables/libraries (files). So what stays in memory is just those pages that have been used recently. So, code for rarely used vim commands or bash error handling, not used functions in libc, and so on just use up disk space, not memory.

Related Question