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 4 >= 4.3.0, PHP 5)
msg_receive — Recibir un mensaje de la cola de mensajes
Descripción
$queue
, int $desiredmsgtype
, int &$msgtype
, int $maxsize
, mixed &$message
[, bool $unserialize = true
[, int $flags = 0
[, int &$errorcode
]]] )
msg_receive() recibirá el primer mensaje de la cola
especificada por queue del tipo especificado por
desiredmsgtype.
Parámetros
-
queue -
-
desiredmsgtype -
Si
desiredmsgtypees 0, se devolverá el mensaje al frente de la cola. Sidesiredmsgtypees mayor que 0, se devolverá el primer mensaje de ese tipo. Sidesiredmsgtypees menor que 0, se leerá el primer mensaje de la cola con el tipo más bajo menor o igual que el valor absoluto dedesiredmsgtype. Si ningún mensaje concuerda con el criterio, el script esperará hasta que un mensaje apropiado llegue a la cola. Se puede prevenir que se bloquee el script especificandoMSG_IPC_NOWAITen el parámetroflags. -
msgtype -
El tipo de mensaje que fue recibido se almacenará en este parámetro.
-
maxsize -
El tamaño máximo del mensaje aceptado se especifica mediante
maxsize; si el mensaje de la cola es mayor que este tamaño la función fallará (a menos que se establezcaflagscomo está descrito abajo). -
message -
El mensaje recibido será almacenado en
message, a menos que hubiera errores al recibir dicho mensaje. -
unserialize -
Si está establecido a
TRUE, el mensaje es tratado como si fuera serializado usando el mismo mecanismo que el del módulo de sesión. El mensaje será deserializado y después devuelto al script. Esto permite recibir de forma sencilla matrices y objetos complejos desde otros scripts de PHP, o si se está usando el serializador WDDX, desde cualquier fuente compatible con WDDX.Si
unserializeesFALSE, el mensaje será devuelto como cadena segura a nivel binario. -
flags -
El parámetro opcional
flagspermite pasar banderas a la llamada a bajo nivel de msgrcv. Por defecto es 0, pero se puede especificar uno o más de los siguientes valores (añadiéndolos o usando OR).Flag values for msg_receive MSG_IPC_NOWAITSi no hay mensajes del tipo deseado dado por desiredmsgtype, devuelve inmediatamente y no espera. La función fallará y devolverá un valor de tipo integer correspondiente aMSG_ENOMSG.MSG_EXCEPTUsar esta bandera en combinación con un desiredmsgtypemayor que 0 causará que la función reciba el primer mensaje que no sea igual adesiredmsgtype.MSG_NOERRORSi el mensaje es mayor que maxsize, establecer esta bandera truncará el mensaje amaxsizey no enviará un error. -
errorcode -
Si la función falla, el parámetro opcional
errorcodeserá establecido al valor de la variable errno del sistema.
Valores devueltos
Devuelve TRUE en caso de éxito o FALSE en caso de error.
Si se finalizó con éxito, la estructura de datos de la cola de mensajes se actualiza como sigue: msg_lrpid se establece al ID del proceso de llamada, msg_qnum se disminuye en 1 y msg_rtime se establece al momento actual.
Ver también
- msg_remove_queue() - Destruir una cola de mensajes
- msg_send() - Eviar un mensaje a una cola de mensajes
- msg_stat_queue() - Devuelve información desde la estructura de datos de la cola de mensajes
- msg_set_queue() - Establecer información en la estructura de datos de la cola de mensajes
The behaviour of msg_recieve function depends on value of $desiredmsgtype:
If zero: the first message with any $msgtype will be recieved.
Positive: the first message with $msgtype = desiredmsgtype
Negative: the first message with $msgtype <= abs ($desiredmsgtype)
(where "$msgtype" means msgtype the message was sent with)
<?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);
}
}
}
}
?>
continue from my previous note
Showing messages from queue will flip-flop. It means you run once send.php, the message will be shown in terminal ...
... #1. Second time in terminal #2, third terminal #1 and so on.
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);
?>
