Home  >  Article  >  php教程  >  PHP实现多进程并行操作的详解(可做守护进程)

PHP实现多进程并行操作的详解(可做守护进程)

WBOY
WBOYOriginal
2016-06-13 11:48:121037browse

如下所示:

复制代码 代码如下:


/**
 * 入口函数
 * 将此文件保存为 ProcessOpera.php
 * 在terminal中运行 /usr/local/php/bin/php ProcessOpera.php &
 * 查看进程 ps aux|grep php
 */
ProcessOpera("runCode", array(), 8);

/**
 * run Code
 */
function runCode($opt = array()) {
   //需要在守护进程中运行的代码
}

/**
 * $func为子进程执行具体事物的函数名称
 * $opt为$func的参数 数组形式
 * $pNum 为fork的子进程数量
 */
function ProcessOpera($func, $opts = array(), $pNum = 1) {
while(true) {
$pid = pcntl_fork();
if($pid == -1) {
exit("pid fork error");

if($pid) {
static $execute = 0;
$execute++;
if($execute >= $pNum) {
pcntl_wait($status);
$execute--;

} else {
while(true) {
//somecode
$func($opts);
sleep(1);

exit(0);


}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn