功能:

当前进程使用 popen 方法执行“free -g”命令,并从输出中提取“used”值。

snippet.c
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
 
int main(int argc, char **argv)
{
    char mem_uesed_def[] = {"0"};
    char *mem_used = mem_uesed_def;
 
    // mem used
    bool b_free = false;
    char buf_ps[512] = {0};
    FILE *f_free = popen("free -m", "r");
    if (f_free) {
    	while (fgets(buf_ps, 512, f_free)) {
        if (strlen(buf_ps) > 4 && strncasecmp(buf_ps, "Mem:", 4) == 0) {
            b_free = true;
            break;
        }
    	}
    	pclose(f_free);
    }
 
    if (b_free) {
    	char *free_ary = NULL;
    	char seps[]  = " ";
    	int free_idx = 0;
    	free_ary = strtok(buf_ps, seps);
    	while (free_ary) {
        if (free_idx == 2) {
            // found mem used
            mem_used = free_ary;
            break;
        }
        free_ary = strtok(NULL, seps);
        ++free_idx;
    	}
    }
 
    printf("memused:%s\n", mem_used);
}

编译与执行:

snippet.bash
[root@yz219 ~]# gcc -o test 1.c
[root@yz219 ~]# ./test
memused:2260