使用 PHP 生成多个进程来处理数据。

mma*_*tax 6 php fork process

我有一个需要处理的数据队列 (Amazon SQS),我想用多个进程(在 PHP 中)来完成。

我希望童工做这样的事情(伪代码):



while(true) {

    $array = $queue->fetchNItems(10); // get 10 items

    if(!count($array)) 
        killProcess();

    foreach($array as $item) {
         ... // process the item
         $queue->remove($item);
    }

    sleep(2);
}


我总是需要运行 1 个子进程,但在需要时我想(fork?)一个子进程,以便它可以帮助更快地处理队列。

有人可以帮助我了解我需要的粗略 PHP 框架,或者指出我正确的方向吗?

我想我需要看看http://php.net/manual/en/function.pcntl-fork.php,但我不确定如何使用它来管理多个进程。

Dev*_*ris 3

当你 fork 一个进程时。您复制该过程。换句话说,副本(分叉)包含原始进程拥有的所有内容(包括文件句柄)

那么你怎么知道你是父进程还是分叉进程呢?

链接页面的示例清楚地表明了这一点

<?php

$pid = pcntl_fork();
if ($pid == -1) {
     die('could not fork');
} else if ($pid) {
     // we are the parent
     pcntl_wait($status); //Protect against Zombie children
} else {
     // we are the child
}

?>
Run Code Online (Sandbox Code Playgroud)

将其扩展到您想要的

<?php

$pid = pcntl_fork();
if ($pid == -1) {
     die('could not fork');
} else if ($pid) {
     // we are the parent
     pcntl_wait($status); //Protect against Zombie children
} else {
     // we are the child
     while(true) {

         $array = $queue->fetchNItems(10); // get 10 items

         if(!count($array)) {
            exit();
         }

         foreach($array as $item) {
              ... // process the item
              $queue->remove($item);
         }

         sleep(2);
     }
}

?>
Run Code Online (Sandbox Code Playgroud)

这将在分叉进程上创建(在本例中是浪费),使用循环来创建多个进程。当子进程完成时退出将杀死子进程。pcntl_wait() 将返回,允许父进程继续。我不确定 php 但如果父进程死亡或退出,即使子进程尚未完成,它也会杀死子进程。因此出现了 pcntl_wait。如果您生成多个子项,则需要更复杂的系统。

也许您应该查看 exec 函数的范围而不是分叉?

一个警告。

分叉进程可能会出现问题,当子进程退出时数据库句柄被关闭等。如果出现问题,您还可以杀死具有多个进程的服务器。花很多时间去玩、测试和阅读。

直流