Linux 下实现 PHP 多进程的方法分享
PHP 多进程:使用 PHP 的 Process Control Functions(PCNTL/线程控制函数),需要的朋友可
以参考下
PHP 多进程:使用 PHP 的 Process Control Functions(PCNTL/线程控制函数)
函数参考可见:
只能用在
Unix Like OS,Windows 不可用。
编译
php 的时候,需要加上–enable-pcntl,且推荐仅仅在 CLI 模式运行,不要在 WEB 服务
器环境运行。
以下为实现
PHP 多进程的简单测试代码:
代码如下
:
<?php
declare
(ticks=1);
$bWaitFlag
= FALSE;
/// 是否等待进程结束
$intNum
= 10;
/// 进程总数
$pids
=
array
();
/// 进程 PID 数组
echo
("Start\n");
for
(
$i
= 0;
$i
<
$intNum
;
$i
++) {
$pids
[
$i
] = pcntl_fork();
/// 产生子进程,而且从当前行之下开试运行代码,而且不继承父进
程的数据信息
if
(!
$pids
[
$i
]) {
// 子进程进程代码段_Start
$str
="";
sleep(5+
$i
);
for
(
$j
=0;
$j
<
$i
;
$j
++) {
$str
.="*";}
echo
"$i -> " . time() . " $str \n";
exit
();
// 子进程进程代码段_End
}
}
if
(
$bWaitFlag
)
{
for
(
$i
= 0;
$i
<
$intNum
;
$i
++) {
pcntl_waitpid(
$pids
[
$i
],
$status
, WUNTRACED);