tasoft/process

v1.0.1 2021-06-22 18:05 UTC

This package is auto-updated.

Last update: 2024-09-23 01:18:34 UTC


README

这个库通过PHP扩展 pcntl 控制进程管理。

安装

$ composer require tasoft/process
简单用法
<?php
use TASoft\Util\Process;

$process = new Process(function() {
    // Do stuff
});

// Now it will fork the process and call the callback function in separate process.
$process->run();

// Do other stuff in main process

// Wait until the child process has done
$process->wait();
// or kill the child process immediately.
$process->kill();
问题

主要问题是派生进程在环境的精确副本中运行。
这意味着,在调用 $process->run() 时,子进程会获得当前环境的副本。

这引发了两个问题

  1. 你在子进程中更改的任何内容(属性、$变量等)都将保留在那里。
  2. 你在父进程中更改的任何内容也将保留在那里。
解决方案

我使用了Pipe类。它创建了一个Unix套接字对,用于两个进程之间的通信。

使用Pipe的示例
<?php
use TASoft\Util\Process;

$process = new Process(function(Process $childProcess) {
    $result = NULL;
    
    // Do hard stuff
    
    // Please don't import the parent process!
    $childProcess->sendData( $result );
});

$process->run();

// Do other stuff

$data = $process->receiveData();
echo $data;

$process->wait(); // or kill

不要导入父进程!

<?php
use TASoft\Util\Process;

$process = new Process(function() use (&$process) {
    $result = NULL;
    // Do stuff
    $process->sendData( $result );
    
    // This is wrong and will not work because $process IS A COPY OF THE MAIN PROCESS!
});

...