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";
}
?>
相关推荐
jllllyuz1 分钟前
基于帧差法与ViBe算法的MATLAB前景提取
开发语言·算法·matlab
DsirNg2 分钟前
CategoryTree 性能优化完整演进史
开发语言·前端
2501_944446003 分钟前
Flutter&OpenHarmony字体与排版设计
android·javascript·flutter
消失的旧时光-19437 分钟前
mixin 写一个 Flutter 的“埋点 + 日志 + 性能监控”完整框架示例
android·flutter
kevin_水滴石穿22 分钟前
C#获取程序集和文件版本
开发语言·c#
we1less23 分钟前
[audio] AudioTrack (五) 共享内存创建分析
android·java·开发语言
傻啦嘿哟27 分钟前
实战:用GraphQL接口高效采集数据
开发语言·驱动开发·php
JIngJaneIL27 分钟前
基于java + vue连锁门店管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
hslinux28 分钟前
NDK 通过configure 编译C++源码通用脚本
android·c++·ndk·configure
秃了也弱了。29 分钟前
python实现离线文字转语音:pyttsx3 库
开发语言·python