ubuntu 获取PHP中的可用内存

fdbelqdn  于 2022-11-02  发布在  PHP
关注(0)|答案(1)|浏览(208)

我有一个PHP脚本可以触发机器上其他进程(Chromium示例)的启动,我想知道我是否可以获得当前系统的可用内存,这样我就可以安全地启动另一个进程,而不会达到内存限制(例如,这可能会导致正在运行的Redis示例出现其他问题)。
我是否必须直接通过exec()执行某种系统调用?

zpjtge22

zpjtge221#

你可以读/proc/meminfo
示例如下

MemTotal:        4025840 kB
MemFree:         1189212 kB
MemAvailable:    1984948 kB
Buffers:          105404 kB
Cached:           883880 kB
SwapCached:        22012 kB
Active:           652224 kB
Inactive:        2055408 kB
Active(anon):      23560 kB
Inactive(anon):  1714568 kB
Active(file):     628664 kB
Inactive(file):   340840 kB
Unevictable:           0 kB
Mlocked:               0 kB
SwapTotal:       2097148 kB
SwapFree:        1881452 kB
Dirty:                16 kB
Writeback:             0 kB
AnonPages:       1691600 kB
Mapped:           125292 kB
Shmem:             19780 kB
KReclaimable:      62736 kB
Slab:              88052 kB
SReclaimable:      62736 kB
SUnreclaim:        25316 kB
KernelStack:        2912 kB
PageTables:        11144 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:     4110068 kB
Committed_AS:    2819784 kB
VmallocTotal:   34359738367 kB
VmallocUsed:       15344 kB
VmallocChunk:          0 kB
Percpu:             1472 kB
HardwareCorrupted:     0 kB
AnonHugePages:   1536000 kB
ShmemHugePages:        0 kB
ShmemPmdMapped:        0 kB
FileHugePages:         0 kB
FilePmdMapped:         0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
Hugetlb:               0 kB
DirectMap4k:      112492 kB
DirectMap2M:     4081664 kB
DirectMap1G:     2097152 kB

编辑:下面是一些关于如何获取值的示例代码,取自here

// mem usage
$get_meminfo = file('/proc/meminfo');

$meminfo_total = filter_var($get_meminfo[0], FILTER_SANITIZE_NUMBER_INT);
$meminfo_cached = filter_var($get_meminfo[2], FILTER_SANITIZE_NUMBER_INT);
$meminfo_free = filter_var($get_meminfo[1], FILTER_SANITIZE_NUMBER_INT);

if ($meminfo_total >= 10485760) {
    $mem_total = round(($meminfo_total / 1048576), 2);
    $mem_cached = round(($meminfo_cached / 1048576), 2);
    $mem_free = round((($meminfo_free + $meminfo_cached) / 1048576), 2);
    $mem_multiple = 'GB';
} else {
    $mem_total = round(($meminfo_total / 1024), 2);
    $mem_cached = round(($meminfo_cached / 1024), 2);
    $mem_free = round((($meminfo_free + $meminfo_cached) / 1024), 2);
    $mem_multiple = 'MB';
}

$mem = array(
    'total' => $mem_total,
    'cached' => $mem_cached,
    'free' => $mem_free
);

相关问题