Ciomco
Ciomco

Reputation: 33

How does Linux know how much physical memory is used by a process?

I was investigating memory usage of an example process. First I allocate some memory, check what is the size of virtual memory and resident memory (in RAM). Then I write data to the allocated memory and check again these values.

int main()
{
 int pid = getpid();
 std::stringstream s;
 s << "cat /proc/" << pid << "/status | grep \"VmSize\\|VmRSS\"";
 std::string command = s.str();
 std::cout << "Before allocation\n";
 system(command.c_str());
 char* mem = new char[10000000];
 std::cout << "After allocation\n";
 system(command.c_str());
 memset(mem, 0, 10000000);
 std::cout << "After writing\n";
 system(command.c_str());
 return 0; 
}

Output:

Before allocation
VmSize:     3412 kB
VmRSS:       852 kB
After allocation
VmSize:    13180 kB
VmRSS:       852 kB
After writing
VmSize:    13180 kB
VmRSS:     10568 kB

When memory is allocated by operator new, only the value of VmSize changes. When data is written to the memory, then value of VmRSS changes. How does Linux know how much physical memory (VmRSS) is used by a process?

Upvotes: 3

Views: 975

Answers (1)

eerorika
eerorika

Reputation: 238461

How does Linux know how much physical memory (VmRSS) is used by a process?

When the process tries to access virtual memory that has not been mapped to physical memory, the CPU (assuming it has a hardware memory management unit) will trigger an interrupt (specifically, a page fault) that is handled by the operating system. The operating system allocates the physical memory to the process and updates the translation look aside buffer (part of the MMU, which is used to map virtual memory to physical).

So, since it is the operating system that allocates the physical memory, it can also track how much it has allocated to each process.

Upvotes: 4

Related Questions