msg_receive

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

msg_receiveПолучает сообщение из очереди сообщений

Описание

msg_receive(
    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 в параметре flags.

received_message_type

В этом параметре сохраняется тип полученного сообщения.

max_message_size

Максимальный размер принимаемого сообщения задаётся в параметре max_message_size; если сообщение в очереди больше этого размера, то функция завершается ошибкой (если флаг flags не установили так, как рассказывает описание этого параметра).

message

Полученное сообщение сохраняется в параметре message, если не было ошибок при получении.

unserialize

Если для параметра установили значение true, сообщение рассматривается как сериализованое тем же механизмом, что и в модуле сессий. Сообщение десериализуется, а затем возвращается в скрипт. Это помогает легко получать массивы и сложные объекты из других PHP-скриптов, или, если используется WDDX-сериализатор, из любых совместимых с WDDX источников.

Если для параметра unserialize указали значение false, сообщение возвращается в виде бинарно-безопасной строки.

flags

Необязательный параметр flags разрешает передать флаги в низкоуровневый системный вызов msgrcv. По умолчанию его значение 0, но можно указать одно или несколько следующих значений (путём сложения или через операцию побитового ИЛИ).

Flag values for msg_receive
MSG_IPC_NOWAIT Если нет сообщений, которые удовлетворяют условиям параметра desired_message_type, возвращаться немедленно, а не ждать. Функция завершается ошибкой и возвращает целочисленное значение MSG_ENOMSG.
MSG_EXCEPT Установка этого флага в комбинации с положительным значением параметра desired_message_type, позволяет получить первое сообщение, тип которого не равен значению desired_message_type.
MSG_NOERROR Если размер сообщения превышает значение параметра max_message_size, то установка этого флага приводит к усечению сообщения до значения параметра max_message_size без сигнализирования об ошибке.

error_code

Если функция завершается аварийно, необязательный параметр error_code будет содержать значение системной переменной errno.

Возвращаемые значения

Функция возвращает true, если выполнилась успешно, или false, если возникла ошибка.

При успешном завершении, структура данных очереди сообщений обновляется следующим образом: элемент msg_lrpid содержит идентификатор вызвавшего процесса, msg_qnum уменьшается на 1, а msg_rtime устанавливается в соответствии с текущим временем.

Список изменений

Версия Описание
8.0.0 Параметр queue теперь ожидает экземпляр класса SysvMessageQueue; раньше ожидался ресурс (resource).

Смотрите также

  • msg_remove_queue() - Удаляет очередь сообщений
  • msg_send() - Отправляет сообщение в очередь сообщений
  • msg_stat_queue() - Получает информацию из структуры данных очереди сообщений
  • msg_set_queue() - Устанавливает информацию в структуре данных очереди сообщений

Добавить

Примечания пользователей 5 notes

up
2
marbledore at mail dot ru
14 years ago
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.
up
1
webmaster at toolshed51 dot com
22 years ago
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);?>
up
1
soger
6 years ago
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.
up
0
eimers at mehrkanal dot com
17 years ago
<?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 Messagesfor ($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);      }    }  }}?>
up
0
marvel at post dot cz
17 years ago
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.
To Top