?php
$key=ftok(__FILE__,'a');
//獲取消息隊列
$queue=msg_get_queue($key,0666);
//發(fā)送消息
//msg_send($queue, 1, "Hello, 1");
//接收消息,如果接收不到會阻塞
msg_receive($queue, 1, $message_type, 1024, $message1);
//移除消息
//msg_remove_queue($queue);
//var_dump($message1);
?php
/**
* 這段代碼模擬了一個日常的任務。
* 第一個父進程產(chǎn)生了一個子進程。子進程又作為父進程,產(chǎn)生10個子進程。
* 可以簡化為A -> B -> c,d,e... 等進程。
* 作為A來說,只需要生產(chǎn)任務,然后交給B 來處理。B 則會將任務分配給10個子進程來進行處理。
*
*/
//設定腳本永不超時
set_time_limit(0);
$ftok = ftok(__FILE__, 'a');
$msg_queue = msg_get_queue($ftok);
$pidarr = [];
//產(chǎn)生子進程
$pid = pcntl_fork();
if ($pid) {
//父進程模擬生成一個特大的數(shù)組。
$arr = range(1,100000);
//將任務放進隊里,讓多個子進程并行處理
foreach ($arr as $val) {
$status = msg_send($msg_queue,1, $val);
usleep(1000);
}
$pidarr[] = $pid;
msg_remove_queue($msg_queue);
} else {
//子進程收到任務后,fork10個子進程來處理任務。
for ($i =0; $i10; $i++) {
$childpid = pcntl_fork();
if ($childpid) {
$pidarr[] = $childpid; //收集子進程processid
} else {
while (true) {
msg_receive($msg_queue, 0, $msg_type, 1024, $message);
if (!$message) exit(0);
echo $message.PHP_EOL;
usleep(1000);
}
}
}
}
//防止主進程先于子進程退出,形成僵尸進程
while (count($pidarr) > 0) {
foreach ($pidarr as $key => $pid) {
$status = pcntl_waitpid($pid, $status);
if ($status == -1 || $status > 0) {
unset($pidarr[$key]);
}
}
sleep(1);
}
以上所述是小編給大家介紹的PHP通信-消息隊列使用詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!