How to get the Free Huge Page Count from a C program?

89 Views Asked by At

I'm looking for a function to call from a C program that returns the number of free huge pages.

I've found functions to return the huge page size(s), lots of information on how to use pseudo file system entries, but no man page for a function that returns the same information you get from running:

cat /proc/meminfo | grep '^Huge'

Is there such a thing?

I tried lots of web searches, got lots of information on use of huge pages, but no information on how to write a program that makes a system call to get said information.

1

There are 1 best solutions below

0
atl On

This c code will open the file /proc/meminfo and read the values.

Here is output showing 2 Huge values extracted.

Notice that the entire line of text is read from the file. The line buffer here is static but other efforts can modify to buffer the entire file or other approaches for reading file data.

Notice that the sscanf returns number of assignments made by the format specified. The format specified separates the values to match. For example the text "HugePages_Total" must match or no assignments are made.

Good luck!

gcc -o main main.c 

./main
HugePages_Total: 0
Hugepagesize: 2048 kB

main.c

// gcc -o main main.c

#include <string.h>
#include <stdio.h>

int main()
{
  FILE* fptr = fopen( "/proc/meminfo", "r" );
  if ( fptr )
  {
    while ( !feof( fptr ) )
    {
      long unsigned number = 10;
      char units[10] = {0};
      char line[4096] = {0};
      fgets(line, sizeof(line), fptr );
      if ( sscanf( line, "HugePages_Total: %lu", &number ) == 1 )
      {
        printf( "HugePages_Total: %lu\n", number );
      }
      else if ( sscanf( line, "Hugepagesize: %lu %s", &number, units ) == 2 )
      {
        printf( "Hugepagesize: %lu %s\n", number, units );
        continue;
      }
    }
  }
  return 0;
}