函数名:msg_receive()
适用版本:PHP 4 >= 4.3.0, PHP 5, PHP 7
函数描述:msg_receive() 函数从一个消息队列接收消息。
用法: msg_receive ( int $queue , int $desiredmsgtype , int &$msgtype , int $maxsize , mixed &$message [, bool $unserialize = true [, int $flags = 0 [, int &$errorcode ]]] ) : bool
参数:
- queue: 消息队列标识符,由 msg_get_queue() 函数返回。
- desiredmsgtype: 期望接收的消息类型。
- msgtype: 接收到的消息类型将会存储在此变量中。
- maxsize: 接收消息的最大长度。
- message: 接收到的消息将会存储在此变量中。
- unserialize: 如果设置为 true (默认值),则接收到的消息将会被反序列化。如果设置为 false,则接收到的消息将会被当作字符串处理。
- flags: 可选参数,用于控制接收消息的行为。可以是 MSG_IPC_NOWAIT 或 MSG_EXCEPT 之一,或者它们的按位或运算结果。
- errorcode: 如果发生错误,将会存储错误代码。
返回值:
- 成功时返回 true,失败时返回 false。
示例:
<?php
$queue = msg_get_queue(12345);
// 接收类型为 1 的消息
$msgtype = 1;
$maxsize = 1024;
$message = null;
if (msg_receive($queue, $msgtype, $msgtype, $maxsize, $message)) {
echo "接收到消息:" . $message . "\n";
} else {
echo "接收消息失败\n";
}
?>
上述示例中,我们首先使用 msg_get_queue() 函数获取一个消息队列的标识符,然后使用 msg_receive() 函数从该队列中接收类型为 1 的消息。如果接收成功,则打印出接收到的消息内容;否则,打印出接收失败的提示。
请注意,msg_receive() 函数需要在支持 System V IPC 的操作系统上运行,否则会抛出错误。