There is an invalid bit for each entry in the page table. When the page is attached to the hard drive, the invalid bit is set. Whenever a page is accessed, the MMU (memory management unit inside the processor) throws an exception and the system is responsible for reloading the page in memory. Then the erroneous instruction is re-executed.
Typically, pages that change places are pages that are not often accessed. Each page table entry has one more bit to know when the page was available. How to choose the right page for sharing with this one bit is a big problem, there is a whole chapter about it in the very good operating systems of Andrew Tanenbaum.
You can block the page in RAM with the mlock() system call. If you use mmap() to map a file in memory, this can be done using the MAP_LOCKED flag (see the Manuals).
source share