Is all of the program code loaded into memory when the program is launched or is only what is needed loaded in?
Most modern OS's will load "on demand", so the starting point of the application (main
) will be loaded by the OS, then the OS just kicks off there. When the application jumps to a piece of code that isn't in memory yet, it loads that bit.
After this does this code\set of instructions get swapped in and out of the physical disk as the process gets CPU time or does loaded code stay in memory whilst the program is running?
If the OS decides that some memory is needed it may well throw out some of the code, and reload it when it needs it later [if it's ever needed again - if it was some part of the initialization, it may never get hit again].
If two processes can share the same set of instructions does this mean each process gets a separate code section in its virtual memory space?
It is certainly possible to share the code between multiple copies of the same application. Again, whether a particular OS does this or not depends on the OS. Linux certainly shares code copies from the same application between two (unrelated) processes [obviously, a forked process shares code by definition]. I believe Windows also does.
Shared libraries (".so" and ".dll" files for Linux/Unix and Windows respectively) are also used to share code between processes - the same shared library is used for many different applications.
The Data space is of course separate for each application and shared libraries will also get their own data section per process sharing the library.