首页 Order Swoole4 正文

Swoole4 [协程高级] 进程API

金鹏头像 金鹏 Swoole4 2022-01-02 14:01:21 0 749
导读:协程进程管理由于在协程空间内fork进程会带着其他协程上下文,因此底层禁止了在Coroutine中使用Process模块。可以使用System::exec()或Ru...

协程进程管理

由于在协程空间内 fork 进程会带着其他协程上下文,因此底层禁止了在 Coroutine 中使用 Process 模块。可以使用

  • System::exec()Runtime Hook+shell_exec 实现外面程序运行

  • Runtime Hook+proc_open 实现父子进程交互通信

使用示例

main.php

use Swoole\Runtime;
use function Swoole\Coroutine\run;

Runtime::enableCoroutine(SWOOLE_HOOK_ALL);
run(function () {
    $descriptorspec = array(
        0 => array("pipe", "r"),
        1 => array("pipe", "w"),
        2 => array("file", "/tmp/error-output.txt", "a")
    );

    $process = proc_open('php ' . __DIR__ . '/read_stdin.php', $descriptorspec, $pipes);

    $n = 10;
    while ($n--) {
        fwrite($pipes[0], "hello #$n \n");
        echo fread($pipes[1], 8192);
    }

    fclose($pipes[0]);
    proc_close($process);
});

read_stdin.php

while(true) {
    $line = fgets(STDIN);
    if ($line) {
        echo $line;
    } else {
        break;
    }
}


本文地址:https://www.jinpeng.work/?id=92
若非特殊说明,文章均属本站原创,转载请注明原链接。
广告3

欢迎 发表评论:

  • 请填写验证码

日历

«    2025年4月    »
123456
78910111213
14151617181920
21222324252627
282930

控制面板

您好,欢迎到访网站!
  查看权限
广告2

退出请按Esc键