PHP多进程通信-消息队列使用 向消息队列发送数据和获取数据的测试 B -> c,d,e... 等进程。 * 作为A来说,只需要生产任务,然后交给B 来处理。B 则会将任务分配给10个子进程来进行处理。 * */ //设定脚本永不超时 set_time_limit(0); $ftok = ftok(__FILE__, 'a'); $msg_queue = msg_get_queue($ftok); $pidarr = []; //产生子进程 $pid = pcntl_fork(); if ($pid) { //父进程模拟生成一个特大的数组。 $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; $i<10; $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通信-消息队列使用详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对中文源码网网站的支持!