Posts

Showing posts with the label C program

How can I write a program to trigger memory direct reclaim ?

 Directly triggering memory direct reclaim in a program is generally not recommended, as the Linux kernel's memory management should handle memory reclamation automatically. However, if you have a specific use case that requires manual memory reclamation, you can use the `madvise` system call or `mincore` to influence memory management behavior. Here's a basic example using `madvise` to advise the kernel to reclaim memory: ```c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/mman.h> int main() {     // Allocate memory     size_t size = 100 * 1024 * 1024; // 100 MB     void* mem = malloc(size);     if (mem == NULL) {         perror("malloc");         exit(1);     }     // Use the memory (touch it)     for (size_t i = 0; i < size; i += getpagesize()) {         ((char*)mem)[i] = 0;     }     // Advise the kernel to reclaim memory     madvise(mem, size, MADV_DONTNEED);     // You can also use `madvise` with other flags f