【问题标题】:Unable to get CPU usage information on Mac since CPU Cores is sometimes reported as 0无法在 Mac 上获取 CPU 使用信息,因为 CPU Cores 有时报告为 0
【发布时间】:2021-02-20 22:21:10
【问题描述】:

我有以下函数试图在 Mac 上检索 CPU 使用率:

public function getCPUUsage()
{
        $cpuload = (float)exec("ps -A -o %cpu | awk '{s+=$1} END {print s}'");
        $cpu_cores = (int)exec("sysctl -a | grep 'machdep.cpu.core_count' | awk '{print $2}'");
        return $cpuload / $cpu_cores;
}

当我在修补程序中调用它时,它可以工作:

vpn-self-service mathewparet$ php artisan tinker
usePsy Shell v0.10.4 (PHP 7.3.11 — cli) by Justin Hileman
>>> use SystemInfo;
>>> SystemInfo::getCPUUsage();
=> 9.6
>>> exit
Exit:  Goodbye
vpn-self-service mathewparet$

但是当在控制器中调用它时,它的 cpu_cores 返回为 0

<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use SystemInfo;

class SystemStatusController extends \App\Http\Controllers\Controller
{

    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function __invoke(Request $request)
    {
        $cpu = SystemInfo::getCPUUsage();
        
        return compact('cpu');
    }
}

在 tinker 和控制器中调用相同的方法。但是当通过 tinker cpu cores > 0 调用时(这是我所期望的)但是在控制器上执行相同操作时 cpu cores 返回为 0 导致 getCPUUsage() 中的下一条语句失败并被零除。

【问题讨论】:

  • 这是因为webserver用户(可能是www-data)没有执行命令的权限。为了证明这一点,您可以创建一个仅包含 getCPUUsage() 内容的最小测试 PHP 脚本,然后在浏览器中运行它。
  • 我使用 Laravel Valet 来运行网站。 Valet 和 Tinker 都以同一个用户身份运行。
  • 我刚刚运行了posix_getpwuid(posix_geteuid())['name']; 来查看脚本被调用为哪个用户。在修补程序和网络服务器中都被称为我自己的用户帐户。

标签: php laravel macos cpu


【解决方案1】:

最后,我用python完成了。

$cpu_cores = (int)exec("python -c 'import multiprocessing as mp; print(mp.cpu_count())'");

【讨论】:

    猜你喜欢
    • 2011-01-12
    • 2020-04-03
    • 2015-11-28
    • 2011-09-05
    • 1970-01-01
    • 2017-03-11
    • 2011-01-28
    • 2013-03-06
    • 1970-01-01
    相关资源
    最近更新 更多