CakeFest 2024: The Official CakePHP Conference

msg_send

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

msg_sendОтправка сообщения в очередь сообщений

Описание

msg_send(
    SysvMessageQueue $queue,
    int $message_type,
    string|int|float|bool $message,
    bool $serialize = true,
    bool $blocking = true,
    int &$error_code = null
): bool

msg_send() отправляет сообщение message с типом message_type (должно быть больше 0) в очередь сообщений, указанную параметром queue.

Список параметров

queue

Очередь сообщений.

message_type

Тип сообщения. Должно быть больше 0.

message

Тело сообщения.

Замечание:

Если serialize задано как false, ДОЛЖНО быть типа: string, int, float или bool. Иначе будет выведено предупреждение.

serialize

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

blocking

Если помещаемое в очередь сообщение слишком велико, ваш скрипт будет ожидать прочтения сообщений другим процессом и освобождения места под отправляемое вами сообщение. Это называется блокировкой; вы можете отключить эту возможность, установив для blocking значение false, в этом случае msg_send() будет немедленно возвращать false если сообщение слишком велико, и устанавливать необязательный параметр error_code в значение MSG_EAGAIN, что будет указывать вам на необходимость попробовать отправить сообщение несколько позже.

error_code

Если функция отработает неудачно, то этот код будет записан в системную переменную errno.

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

Возвращает true в случае успешного выполнения или false, если возникла ошибка.

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

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

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

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

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

add a note

User Contributed Notes 6 notes

up
5
Muffinman
11 years ago
When sending non-complex (serialize = false) messages to a program in C, you need to add the null character to the string (\0). Otherwise the previous message will be partially visible if it is longer than the current message. Took some kind help from comp.lang.php for me to figure that out. While it seems so obvious now, I thought I'd share it here.
up
5
qeekin at gmail dot com
9 years ago
I created example how to comunnicate with programe written in C throught messages queues. First run C program (it will create queue) then PHP script.

C code compile with: gcc -std=c99 -o test_queue test_queue.c

test_queue.c:
/**
* Example how to use System V Messages Queues with PHP and C program.
* This is simple server which create message queue and receive message from it.
* Based on Beej's Guide to Unix IPC
* Autor: Jan Drazil, <qeekin at gmail dot com>
*/

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

/* Buffer struct for receiving messages */
struct php_buf {
long mtype;
char msg[200];
};

int main(void)
{
struct php_buf buf;
int msqid;
key_t key;

/* Generate key (/var/www/index.php must be accessible file) */
if((key = ftok("/var/www/index.php", 'G')) == -1) {
perror("ftok");
exit(EXIT_FAILURE);
}

/* Create message queue */
if((msqid = msgget(key, 0666 | IPC_CREAT)) == -1) {
perror("msgget");
exit(EXIT_FAILURE);
}

printf("Ready to get string from PHP!\n");

/* Receive message */
if(msgrcv(msqid, &buf, sizeof(buf.msg)-1, 0, 0) == -1) {
perror("msgrcv");
exit(EXIT_FAILURE);
}

/* Eliminate segmentation fault */
buf.msg[199] = '\0';

printf("Recieved from PHP: %s\n", buf.msg);

/* Destroy message queue */
if(msgctl(msqid, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(EXIT_FAILURE);
}

return EXIT_SUCCESS;
}

test_queue.php:
<?php
/**
* Example how to use System V Messages Queues with PHP and C program.
* This is simple server which create message queue and receive message from it.
* Based on Beej's Guide to Unix IPC
* Autor: Jan Drazil, <qeekin at gmail dot com>
*/

/* Generate key, param fot ftok must be same as in test_msg.c */
if(($key = ftok("/var/www/index.php", "G")) == -1)
die(
"ftok");

if(!
msg_queue_exists($key))
die(
"message queue doesn't exists");

/* Connect to message queue */
if(($msqid = msg_get_queue($key)) === FALSE)
die(
"msg_get_queue");

echo
"Sending text to msg queue.\n";

/* Send message to C program */
if(!msg_send($msqid, 12, "Hello from PHP!\0", false))
die(
"msg_send");

echo
"Done"
?>
up
1
michael dot NO dot SP dot AM dot cordover+php at gmail dot com
14 years ago
After about an hour of debugging I've discovered the meaning of the undocumented "PHP Warning: msg_send(): msgsnd failed: Invalid argument" ($errorcode = 13).

This occurred when the size of $message was larger than msg_qbytes (see msg_stat_queue() for how to determine and change msg_qbytes).
up
0
shepik at yandex dot ru
14 years ago
$msgtype used in msg_send function can be any positive integer.
up
-1
webmaster at toolshed51 dot com
20 years ago
Sample sending webpage, see msg_receive for matching service

<?php
$MSGKEY
= 519051;

$msg_id = msg_get_queue ($MSGKEY, 0600);

if (!
msg_send ($msg_id, 1, 'Hi', true, true, $msg_err))
echo
"Msg not sent because $msg_err\n";
?>
up
-1
bryan-boone at msn dot com
15 years ago
I think it is kinda lame why I cannot find out (easily) explicitly which types of messages are allowed and which ones are not. Maybe we can start our own little list. I know that strings work, and arrays do not.
To Top