It looks like msg_receive() allocates a memory with size $maxsize, and only then tries to receive a message from queue into allocated memory. Because my script dies with $maxsize = 1 Gib, but works with $maxsize = 10 Kib.msg_receive
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
msg_receive
Референца за `function.msg-receive.php` со подобрена типографија и навигација.
msg_receive
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
msg_receive — Прими порака од опашка за пораки
= NULL
SysvMessageQueue
$queue,int
$desired_message_type,int
&$received_message_type,int
$max_message_size,mixed
&$message,bool
$unserialize = true,int
$flags = 0,int
&$error_code = null): bool
msg_receive() ќе ја прими првата порака од наведената queue од типот наведен од
desired_message_type.
Параметри
queue- Редот за пораки.
desired_message_type-
Враќа
desired_message_typeе 0, се враќа пораката од предниот дел на опашката. Акоdesired_message_typeе поголемо од 0, тогаш се враќа првата порака од тој тип. Акоdesired_message_typeе помало од 0, првата порака на опашката со тип помал или еднаков на апсолутната вредност наdesired_message_typeќе се прочита. Ако нема пораки што ги исполнуваат критериумите, вашиот скрипт ќе чека додека не пристигне соодветна порака на опашката. Можете да го спречите скрипт да блокира со наведувањеMSG_IPC_NOWAITвоflagsparameter. received_message_type- Типот на примена порака ќе биде зачуван во овој параметар.
max_message_size-
Максималната големина на пораката што ќе биде прифатена е наведена од
max_message_size; if the message in the queue is larger than this size the function will fail (unless you setflagsкако што е опишано подолу). message-
Примената порака ќе биде зачувана во
message, освен ако нема грешки при примањето на пораката. unserialize-
Ако е поставено на
true, пораката се третира како да е серијализирана користејќи го истиот механизам како модулот за сесии. Пораката ќе биде десеријализирана и потоа вратена на вашиот скрипт. Ова ви овозможува лесно да примате низи или сложени структури на објекти од други PHP скрипти, или ако го користите WDDX серијализаторот, од кој било WDDX компатибилен извор. Враќаunserializeisfalse, пораката ќе биде вратена како бинарно-безбеден стринг. flags-
Опционалниот
flagsви овозможува да поминете знаменца на системскиот повик msgrcv на ниско ниво. Стандардно е 0, но можете да наведете една или повеќе од следниве вредности (со додавање или OR-ирање заедно).Вредности на знаменца за msg_receive MSG_IPC_NOWAITАко нема пораки од desired_message_type, врати веднаш и не чекај. Функцијата ќе откаже и ќе врати цел број што одговара наMSG_ENOMSG.MSG_EXCEPTКористење на ова знаменце во комбинација со desired_message_typeпоголемо од 0 ќе предизвика функцијата да ја прими првата порака што не е еднаква наdesired_message_type.MSG_NOERRORАко пораката е подолга од max_message_size, поставувањето на овој флаг ќе ја скрати пораката наmax_message_sizeи нема да сигнализира грешка. error_code-
Ако функцијата не успее, опционалното
error_codeќе биде поставено на вредноста на системската променлива errno.
Вратени вредности
Патеката до PHP скриптата што треба да се провери. true на успех или false при неуспех.
По успешното завршување, структурата на податоци на редицата за пораки се ажурира на следниов начин: msg_lrpid се поставува на ID-то на процесот на повикувачкиот процес, msg_qnum се намалува за 1 и
msg_rtime се поставува на тековното време.
Дневник на промени
| Верзија | = NULL |
|---|---|
| 8.0.0 |
queue беше вратено при неуспех. SysvMessageQueue
инстанца сега; претходно, а resource се очекуваше.
|
Види Исто така
- msg_remove_queue() - Уништи ред за пораки
- msg_send() - Испрати порака до порака опашка
- msg_stat_queue() Клуч на редицата.
- msg_set_queue() - Set information in the message queue data structure
Белешки од корисници 5 белешки
<?php error_reporting(E_ALL);
/**
* Example for sending and receiving Messages via the System V Message Queue
*
* To try this script run it synchron/asynchron twice times. One time with ?typ=send and one time with ?typ=receive
*
* @author Thomas Eimers - Mehrkanal GmbH
*
* This document is distributed in the hope that it will be useful, but without any warranty;
* without even the implied warranty of merchantability or fitness for a particular purpose.
*/
header('Content-Type: text/plain; charset=ISO-8859-1');
echo "Start...\n";
// Create System V Message Queue. Integer value is the number of the Queue
$queue = msg_get_queue(100379);
// Sendoptions
$message='nachricht'; // Transfering Data
$serialize_needed=false; // Must the transfer data be serialized ?
$block_send=false; // Block if Message could not be send (Queue full...) (true/false)
$msgtype_send=1; // Any Integer above 0. It signeds every Message. So you could handle multible message
// type in one Queue.
// Receiveoptions
$msgtype_receive=1; // Whiche type of Message we want to receive ? (Here, the type is the same as the type we send,
// but if you set this to 0 you receive the next Message in the Queue with any type.
$maxsize=100; // How long is the maximal data you like to receive.
$option_receive=MSG_IPC_NOWAIT; // If there are no messages of the wanted type in the Queue continue without wating.
// If is set to NULL wait for a Message.
// Send or receive 20 Messages
for ($i=0;$i<20;$i++) {
sleep(1);
// This one sends
if ($_GET['typ']=='send') {
if(msg_send($queue,$msgtype_send, $message,$serialize_needed, $block_send,$err)===true) {
echo "Message sendet.\n";
} else {
var_dump($err);
}
// This one received
} else {
$queue_status=msg_stat_queue($queue);
echo 'Messages in the queue: '.$queue_status['msg_qnum']."\n";
// WARNUNG: nur weil vor einer Zeile Code noch Nachrichten in der Queue waren, muss das jetzt nciht mehr der Fall sein!
if ($queue_status['msg_qnum']>0) {
if (msg_receive($queue,$msgtype_receive ,$msgtype_erhalten,$maxsize,$daten,$serialize_needed, $option_receive, $err)===true) {
echo "Received data".$daten."\n";
} else {
var_dump($err);
}
}
}
}
?>It seems that a maxsize of 2Mb is some sort of a threshold for php, above that msg_receive() starts to use a lot of CPU (with a sender that is pushing messages non-stop receiving 10000 messages jumps up from 0.01 sec to 1.5 sec on my computer) so try to stay below that thresholod if you can.Consider this e.g. Linux situation:
<?php
//file send.php
$ip = msg_get_queue(12340);
msg_send($ip,8,"abcd",false,false,$err);
//-----------------------------------------------------
<?php
//file receive.php
$ip = msg_get_queue(12340);
msg_receive($ip,0,$msgtype,4,$data,false,null,$err);
echo "msgtype {$msgtype} data {$data}\n";
msg_receive($ip,0,$msgtype,4,$data,false,null,$err);
echo "msgtype {$msgtype} data {$data}\n";
?>
Now run:
in terminal #1 php5 receive.php
in terminal #2 php5 receive.php
in terminal #3 php5 send.php
Showing messages from queue will flip-flop. It means you run once send.php, the message will be shown in terminal #1. Second run it will be in t#2, third #1 and so on.This is meant to be run as your apache user in a terminal, call script in note of msg_send and they will communicate.
#! /usr/bin/env php
<?php
$MSGKEY = 519051; // Message
$msg_id = msg_get_queue ($MSGKEY, 0600);
while (1) {
if (msg_receive ($msg_id, 1, $msg_type, 16384, $msg, true, 0, $msg_error)) {
if ($msg == 'Quit') break;
echo "$msg\n";
} else {
echo "Received $msg_error fetching message\n";
break;
}
}
msg_remove_queue ($msg_id);
?>