You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows环境下如何检查特定PHP脚本是否处于运行状态

这个问题我之前也碰到过!用tasklist默认确实只显示进程名,看不到具体执行的脚本参数,不过我们可以通过添加参数让它显示完整的命令行信息,或者用更精准的工具来获取。下面分不同平台给你解决方案:

Windows 平台解决方案

方法1:用tasklist显示进程详细信息

tasklist默认不展示命令行参数,加上/V参数就能看到进程的完整启动命令,再用/FI过滤出php.exe进程:

exec('tasklist /V /FI "IMAGENAME eq php.exe" 2>NUL', $output);

接下来遍历输出结果,匹配你要找的脚本文件名即可:

$targetScript = 'php-file.php';
$isRunning = false;

foreach ($output as $line) {
    // 用正则匹配脚本名,兼容不同路径格式
    if (preg_match('/' . preg_quote($targetScript, '/') . '/i', $line)) {
        $isRunning = true;
        break;
    }
}

echo $isRunning ? "脚本{$targetScript}正在运行" : "脚本{$targetScript}已停止";

方法2:用wmic获取结构化命令行数据

wmic比tasklist更适合提取结构化信息,它可以直接输出每个php进程的命令行参数,格式更简洁:

exec('wmic process where name="php.exe" get commandline /value 2>NUL', $output);
$targetScript = 'php-file.php';
$isRunning = false;

foreach ($output as $line) {
    // 输出格式类似:CommandLine=C:\php\php.exe ./php-file.php
    if (strpos($line, $targetScript) !== false) {
        $isRunning = true;
        break;
    }
}

Linux/macOS 平台解决方案

如果是类Unix系统,直接用ps命令就能看到完整的进程命令行:

exec('ps aux | grep php | grep -v grep 2>NUL', $output);
$targetScript = 'php-file.php';
$isRunning = false;

foreach ($output as $line) {
    if (strpos($line, $targetScript) !== false) {
        $isRunning = true;
        break;
    }
}

这里grep -v grep是为了排除掉执行grep php本身产生的进程。

额外建议:记录PID更可靠

如果业务场景允许,启动脚本时把进程ID(PID)记录到文件或数据库里,后续检查时直接通过PID判断进程是否存在,比匹配文件名更精准,还能避免同名脚本的干扰:

// 启动脚本时记录PID(Linux/macOS)
$pid = shell_exec('php ./php-file.php > /dev/null 2>&1 & echo $!');
file_put_contents('script.pid', $pid);

// 检查进程是否运行
$pid = trim(file_get_contents('script.pid'));
$isRunning = false;

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
    // Windows下用tasklist过滤PID
    exec("tasklist /FI \"PID eq $pid\" 2>NUL", $output);
    $isRunning = count($output) > 1; // 只有表头说明进程不存在
} else {
    // Linux/macOS下用kill -0检查PID是否存活
    exec("kill -0 $pid 2>NUL", $_, $exitCode);
    $isRunning = $exitCode === 0;
}

内容的提问来源于stack exchange,提问作者Tuz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:37:01