Using C library APIs to calculate memory reservations

QNX SDP8.0System ArchitectureDeveloperUser

You can use the code snippets in this section to calculate how much private and shared memory your process is using.

Calculating private memory reservations

Set up a notification that reads the value of the private memory of your process when the notification is triggered. In the code snippet below, rsv contains the private memory reservation of the process with the Process ID specified by the pid parameter (in bytes). Return checks have been omitted for simplicity.

int ev_id;
struct sigevent sev;
uint64_t rsv;
SIGEV_NONE_INIT(&sev);
ev_id = procmgr_value_notify_add(PROCMGR_VALUE_PRIVATE_MEM, pid, 0, &sev);
rsv = procmgr_value_current(ev_id);
procmgr_event_notify_delete(ev_id);

Calculating shared memory usage

Collect page data for the process for which /proc/pid/ctl was opened. In this example, fd is proc_fd. The first call to devctl(DCMD_PROC_PAGEDATA) returns the number of entries present in nentries. This value is used to determine the amount of space to allocate for the data in the next step. The space is then populated in the third step. You can use this data to calculate shared memory usage. Return checks have been omitted for simplicity.

#include <sys/procfs.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/mman.h>

uint64_t get_pagedata(const int proc_fd,
                      procfs_mapinfo **mapinfo_buf,
                      int *entries_num)
{
    /* get the number of entries for this process: */
    int nentries;
    devctl(proc_fd, DCMD_PROC_PAGEDATA, NULL, 0, &nentries);

    /* allocate storage */
    procfs_mapinfo *mi_new = calloc(nentries, sizeof(*mi_new));

    /* read data */
    int dummy;
    devctl(proc_fd, DCMD_PROC_PAGEDATA, mi_new,
            sizeof (*mi_new) * nentries, &dummy);

    *entries_num = nentries;
    *mapinfo_buf = mi_new;

    // example of how caller can use values.
    // printf( "Number of page entries read: %d \n", *entries_num);

    uint64_t total_map_shared = 0;

    /* example usage: calculate shared memory for this process */
    for(int i = 0; i < *entries_num; i++) {
        if((mapinfo_buf[i]->flags & (PG_HWMAPPED|MAP_SYSRAM)) ==
                (PG_HWMAPPED| MAP_SYSRAM)) {
            if((mapinfo_buf[i]->flags & MAP_TYPE) == MAP_SHARED) {
                total_map_shared += mapinfo_buf[i]->size;
            }
        }
    }
    return total_map_shared;
}
Page updated: