Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

内存监控任务 在windows下 无法调用posix_getppid 的错误问题 #374

Open
chenpinzhong opened this issue Jun 3, 2023 · 1 comment

Comments

@chenpinzhong
Copy link

Error: Call to undefined function process\posix_getppid() in D:\UI\d2wd-server\process\Monitor.php:182

process\Monitor的这个文件 在windows下 无法调用posix_getppid

177行
/**
* @param $memory_limit
* @return void
*/
public function checkMemory($memory_limit)
{
if (static::isPaused()) {
return;
}
$ppid = posix_getppid();

@chenpinzhong
Copy link
Author

我这样改了一下
/**
* @param $memory_limit
* @return void
*/
public function checkMemory($memory_limit)
{
if (static::isPaused()) {
return;
}

    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        // Windows 系统
        // 在 Windows 上,无法使用 posix_getppid() 函数获取父进程的进程ID
        // 可以使用其他方法获取父进程的进程ID,如通过 WMI 或其他系统调用
        $ppid = getmypid(); // 自定义函数,用于获取父进程的进程ID
        $output = [];
        $mem=0;
        exec("tasklist /FI \"PID eq $ppid\" /FO CSV", $output);
        if (isset($output[1])) {
            $processInfo = str_getcsv($output[1]);
            if (isset($processInfo[4])) {
                $mem = (float) str_replace(",", "", $processInfo[4]);
            }
        }
        $mem = (int)($mem / 1024);
        if ($mem >= $memory_limit) {
            exec("taskkill /F /PID $ppid", $output, $exitCode);
        }
    } else {
        // 非 Windows 系统
        // 在其他操作系统上,可以使用 posix_getppid() 函数获取父进程的进程ID
        $ppid = posix_getppid();
        $children_file = "/proc/$ppid/task/$ppid/children";
        if (!is_file($children_file) || !($children = file_get_contents($children_file))) {
            return;
        }
        foreach (explode(' ', $children) as $pid) {
            $pid = (int)$pid;
            $status_file = "/proc/$pid/status";
            if (!is_file($status_file) || !($status = file_get_contents($status_file))) {
                continue;
            }
            $mem = 0;
            if (preg_match('/VmRSS\s*?:\s*?(\d+?)\s*?kB/', $status, $match)) {
                $mem = $match[1];
            }
            $mem = (int)($mem / 1024);
            if ($mem >= $memory_limit) {
                posix_kill($pid, SIGINT);
            }
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant