jwaliszko
jwaliszko

Reputation: 17074

VirtualQueryEx alternative for Linux - how to get virtual memory range of another process

I went through this blog and this videocast. In Windows if I want to retrieve information about a range of pages within the virtual address space of a specified process, I can use WinAPI VirtualQueryEx method:

MEMORY_BASIC_INFORMATION meminfo;
unsigned char *addr = 0;
for(;;)
{
    if(!VirtualQueryEx(hProc, addr, &meminfo, sizeof(meminfo)))
        break;
    if(meminfo.State & MEM_COMMIT)
    {
        //collect some data from meminfo
    }
    addr = (unsigned char*)meminfo.BaseAddress + meminfo.RegionSize;
}

I wondered how to get similar set of information in Linux using syscalls, but it is not clear for me how using C/C++ can I gather such a data under Linux. I went through this thread when there are suggestions to take a look at /proc/<pid>/mem or /proc/<pid>/maps files. Is it the good direction? How should look the closest implementation to this one provided here, but for Linux?

Upvotes: 1

Views: 2227

Answers (2)

Igor Skochinsky
Igor Skochinsky

Reputation: 25308

As far as I know /proc/<pid>/maps is the only reliable and supported way to do it. Even libunwind is using it:

  if (maps_init (&mi, getpid()) < 0)
    return -1;

  unsigned long offset;
  while (maps_next (&mi, &low, &hi, &offset)) {
    struct dl_phdr_info info;
    info.dlpi_name = mi.path;
    info.dlpi_addr = low;

Upvotes: 1

rodrigo
rodrigo

Reputation: 98436

Yes, the proc filesystem is part of the Linux API, so this is the way to go. A lot of data in that filesystem is usually accessed using a library wrapper, but that's where the data lie.

Upvotes: 1

Related Questions