PHP开启多进程

amphp/parallel是一个可以在PHP中并行处理任务的库。你可以使用它来启动和管理子进程。

核心代码:

php 复制代码
<?php
$phpCode = <<<'PHP'
<?php
// 子进程:初始化状态
$status = "wait";

// 子进程:创建一个循环,等待指令
while (true) {
    // 从 stdin 读取指令
    $command = trim(fgets(STDIN));

    if ($command === "stop") {
        $status = "stopped";
        echo "Process stopped\n";
        break;
    } elseif ($command === "status") {
        echo "Current status: $status\n";
    } elseif ($command === "start") {
        $status = "running";
        echo "Process started\n";
    } else {
        echo "Unknown command: $command\n";
    }
}
?>
PHP;

// 创建一个临时文件来存储 PHP 代码
$tempFile = tempnam(sys_get_temp_dir(), 'phpcode');
file_put_contents($tempFile, $phpCode);

$descriptorspec = array(
    0 => array("pipe", "r"),  // stdin 是一个管道,由子进程读取
    1 => array("pipe", "w"),  // stdout 是一个管道,由子进程写入
    2 => array("pipe", "w")   // stderr 是一个管道,由子进程写入
);

// 启动子进程
$process = proc_open("php $tempFile", $descriptorspec, $pipes);

if (is_resource($process)) {
    // 设置 stdout 为非阻塞模式
    stream_set_blocking($pipes[1], false);

    // 父进程:发送指令给子进程并读取输出
    function sendCommand($pipes, $command) {
        fwrite($pipes[0], $command . "\n");
        fflush($pipes[0]); // 确保数据被发送

        $output = '';
        $timeout = 2; // 超时时间(秒)
        $start_time = time();

        // 使用 fgets 逐行读取子进程的输出
        while (true) {
            $line = fgets($pipes[1]);
            if ($line === false) {
                // 检查是否超时
                if (time() - $start_time > $timeout) {
                    break;
                }
                usleep(100000); // 等待子进程处理
            } else {
                $output .= $line;
                if (strpos($line, "\n") !== false) {
                    break;
                }
            }
        }

        return $output;
    }

    echo sendCommand($pipes, "status");
    echo sendCommand($pipes, "start");
    echo sendCommand($pipes, "status");
    echo sendCommand($pipes, "stop");

    // 关闭管道
    fclose($pipes[0]);
    fclose($pipes[1]);
    fclose($pipes[2]);

    // 关闭子进程并获取退出码
    $return_value = proc_close($process);

    // 删除临时文件
    unlink($tempFile);

    echo "Command returned $return_value\n";
}
?>
相关推荐
嵌入式-老费10 分钟前
自己动手写深度学习框架(快速学习python和关联库)
开发语言·python·学习
Y多了个想法15 分钟前
Linux驱动开发与Android驱动开发
android·linux·驱动开发
ctgu9017 分钟前
PyQt5(八):ui设置为可以手动随意拉伸功能
开发语言·qt·ui
AI浩24 分钟前
深入级联不稳定性:从 Lipschitz 连续性视角探讨图像恢复与目标检测的协同作用
人工智能·目标检测·php
CVer儿25 分钟前
libtorch ITK 部署 nnUNetV2 模型
开发语言
asyxchenchong88833 分钟前
OpenLCA、GREET、R语言的生命周期评价方法、模型构建
开发语言·r语言
没有梦想的咸鱼185-1037-16631 小时前
【生命周期评价(LCA)】基于OpenLCA、GREET、R语言的生命周期评价方法、模型构建
开发语言·数据分析·r语言
程序猿20231 小时前
Python每日一练---第三天:删除有序数组中的重复项
开发语言·python
一只游鱼1 小时前
Springboot+BannerBanner(启动横幅)
java·开发语言·数据库
一只游鱼1 小时前
抖音上的用python实现激励弹窗
开发语言·python