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";
}
?>
相关推荐
峥嵘life1 小时前
Android16 【CTS】CtsMediaCodecTestCases等一些列Media测试存在Failed项
android·linux·学习
qq_336313931 小时前
javaweb-web基础(springboot入门)
java·开发语言·mysql
玄同7651 小时前
LangChain 1.0 模型接口:多厂商集成与统一调用
开发语言·人工智能·python·langchain·知识图谱·rag·智能体
特立独行的猫a1 小时前
C++轻量级Web框架介绍与对比:Crow与httplib
开发语言·前端·c++·crow·httplib
fie88891 小时前
基于C#的推箱子小游戏实现
开发语言·c#
菜鸟小芯1 小时前
Qt Creator 集成开发环境下载安装
开发语言·qt
stevenzqzq2 小时前
Compose 中的状态可变性体系
android·compose
阿猿收手吧!2 小时前
【C++】引用类型全解析:左值、右值与万能引用
开发语言·c++
「QT(C++)开发工程师」2 小时前
C++ 策略模式
开发语言·c++·策略模式
iFeng的小屋2 小时前
【2026最新当当网爬虫分享】用Python爬取千本日本相关图书,自动分析价格分布!
开发语言·爬虫·python