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

msg_get_queue

msg_get_queue() возвращает идентификатор, который используется для доступа к очереди сообщений System V с указанным ключом key . Первый вызов создаёт очередь сообщений с необязательными правами permissions . Второй и последующие вызовы msg_get_queue() для того же key будут возвращать другие идентификаторы, однако все они будут ссылаться на одну и ту же очередь сообщений.

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

Числовой идентификатор очереди сообщений.

Права доступа к очереди. По умолчанию 0666. Если очередь сообщений уже существует, параметр permissions игнорируется.

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

Возвращает экземпляр SysvMessageQueue , который может быть использован для доступа к очереди сообщений System V или false в случае возникновения ошибки.

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

Версия Описание
8.0.0 В случае успешного выполнения функция теперь возвращает экземпляр SysvMessageQueue ; ранее возвращался ресурс ( resource ).

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

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

User Contributed Notes 7 notes

If you are getting the following message (on Linux):

Warning: msg_get_queue() [function.msg-get-queue]: failed for key 0x12345678: No space left on device in /path/to/script.php on line 1

aside from what [others have] suggested, you should also check and set an appropriate value for kernel parameter kernel.msgmni, e.g. sysctl -w kernel.msgmni=256

If you are getting this message on your *NIX box:

Warning: msg_get_queue() [function.msg-get-queue]: failed for key 0x12345678: No space left on device in /path/to/script.php on line 1

you may use the command «ipcrm» as root to clear the message queue. Use «man ipcrm» to get more info on it.
The default setting for maximum messages in the queue is stored in /proc/sys/fs/mqueue/msg_max. To increase it to a maximum of 100 messages, just run:
echo 100 > /proc/sys/fs/mqueue/msg_max

Читайте также:  Слайдер на php и jquery

Please ensure to follow a good programming style and close/free all your message queues before your script exits to avoid those warning messages.

A simple Sample to introduce Message Queue.

if ( sizeof ( $argv ) < 2 ) <
echo «Usage: $argv [ 0 ] stat|send|receive|remove msgType MSG [msg] \n\n» ;
echo » EX: $argv [ 0 ] send 1 \»This is no 1\» \n» ;
echo » $argv [ 0 ] receive ID \n» ;
echo » $argv [ 0 ] stat \n» ;
echo » $argv [ 0 ] remove \n» ;
exit;
>

## Create or attach to a message queue
$seg = msg_get_queue ( $MSGKey ) ;

switch ( $argv [ 1 ] ) <
case «send» :
msg_send ( $seg , $argv [ 2 ], $argv [ 3 ]);
echo «msg_send done. \n» ;
break;

case «receive» :
$stat = msg_stat_queue ( $seg );
echo ‘Messages in the queue: ‘ . $stat [ ‘msg_qnum’ ]. «\n» ;
if ( $stat [ ‘msg_qnum’ ]> 0 ) <
msg_receive ( $seg , $argv [ 2 ], $msgtype , 1024 , $data );
var_dump ( $msgtype );
var_dump ( $data );
echo «\n» ;
>
else <
echo «No Msg. \n» ;
>
break;

case «stat» :
print_r ( msg_stat_queue ( $seg ) );
break;

case «remove» :
msg_remove_queue ( $seg );
break;
>
?>

I find it hard to work out how to really use this reliably particularly in respect to collisions.

It maps to SysV IPC msgget.

As I see it you have three options.

1. Manage the IDs yourself, allocating various ranges or using some kind of centralised mechanism.
2. Use ftok. This attempts to find a unique ID, though it’s not guaranteed to be unique or constant in absolutely every circumstance. It relies on using a file, from which it uses bits from the inode and dev it expects to be unique. It’s the standard way and as long as there’s nothing too unusual it should probably work (but might not survive radical FS changes).
3. Use 0 as the key, which appears to map to IPC_PRIVATE, a magic value which if provided as a key creates a new queue each time (without a key in effect).

Unfortunately option #3 is of limited use in PHP.

In C that is useful might be useful as the queue resource is just identified by an int and can be passed around.

Читайте также:  Datetime python month years

In PHP its utility is questionable as only the resource can be passed within a single process. It’s not possible to pass the resource with serialize / unserialize even though it’s just a wrapped int.

The msqid returned isn’t exactly unpredictable either so can quite easily be accidentally accessed. The first one I got was 0.

If you create a queue like this you’ll find it very annoying as it wont be possible to delete it via PHP.

Like all IO it’s worth wrapping this function and launching an exception if the input is 0.

Lack of IPC_EXCL makes me unhappy. Of course, you can use ftok() to generate a unique key. This code is not allmighty, another process under the same user can open the queue and function returns true. But in some situation it could help.

function ipcEXCL($res,$perm)
$pole = msg_stat_queue($res);

if(ipcEXCL($res,$perm))
echo «probably I am a creator:»;
else
echo «probably not»;
?>

// Here is an example of working with message queues.
// if you have forked processes, this could be a great way of passing
// out work to them

// create the message queue
// pick a file..
$key_t = msg_get_queue(ftok(«/tmp/php_msgqueue.stat», ‘R’),0666 | IPC_CREAT);

// place two messages on the queue
if (!msg_send ($key_t, 1, ‘This is message #1’, true, true, $msg_err))
echo «Msg not sent because $msg_err\n»;
if (!msg_send ($key_t, 1, ‘This is message #2 ‘, true, true, $msg_err))
echo «Msg not sent because $msg_err\n»;

// lets look at the queue structure ‘msg_qnum’ is really what we want to see
// it should be ‘2’
print_r(msg_stat_queue($key_t));

// pull off the stack
if (msg_receive ($key_t, 1, $msg_type, 16384, $msg, true, 0, $msg_error)) if ($msg == ‘Quit’);
echo «$msg\n»; // prints ‘This is message #1’
> else echo «Received $msg_error fetching message\n»;
>
// look at the structure again, ms_qnum should be ‘1’
print_r(msg_stat_queue($key_t));
if (msg_receive ($key_t, 1, $msg_type, 16384, $msg, true, 0, $msg_error)) if ($msg == ‘Quit’);
echo «$msg\n»; // prints ‘This is message #2’
> else echo «Received $msg_error fetching message\n»;
>
// look at the structure again, ms_qnum should be ‘0’, no more messages on the queue
print_r(msg_stat_queue($key_t));

Читайте также:  Php file in html page

// get rid of the queue we created
msg_remove_queue ($key_t);

IPC_CREAT has no effect in this function. The PHP source code (file sysvmsg.c) reveals that only if msgget(key,0) fails, msgget(key, IPC_CREAT | IPC_EXCL | perms) is used.

  • Функции семафоров
    • ftok
    • msg_​get_​queue
    • msg_​queue_​exists
    • msg_​receive
    • msg_​remove_​queue
    • msg_​send
    • msg_​set_​queue
    • msg_​stat_​queue
    • sem_​acquire
    • sem_​get
    • sem_​release
    • sem_​remove
    • shm_​attach
    • shm_​detach
    • shm_​get_​var
    • shm_​has_​var
    • shm_​put_​var
    • shm_​remove_​var
    • shm_​remove

    Источник

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

    В этом разделе помещены уроки по PHP скриптам, которые Вы сможете использовать на своих ресурсах.

    Фильтрация данных с помощью zend-filter

    Когда речь идёт о безопасности веб-сайта, то фраза «фильтруйте всё, экранируйте всё» всегда будет актуальна. Сегодня поговорим о фильтрации данных.

    Контекстное экранирование с помощью zend-escaper

    Обеспечение безопасности веб-сайта — это не только защита от SQL инъекций, но и протекция от межсайтового скриптинга (XSS), межсайтовой подделки запросов (CSRF) и от других видов атак. В частности, вам нужно очень осторожно подходить к формированию HTML, CSS и JavaScript кода.

    Подключение Zend модулей к Expressive

    Expressive 2 поддерживает возможность подключения других ZF компонент по специальной схеме. Не всем нравится данное решение. В этой статье мы расскажем как улучшили процесс подключение нескольких модулей.

    Совет: отправка информации в Google Analytics через API

    Предположим, что вам необходимо отправить какую-то информацию в Google Analytics из серверного скрипта. Как это сделать. Ответ в этой заметке.

    Подборка PHP песочниц

    Подборка из нескольких видов PHP песочниц. На некоторых вы в режиме online сможете потестить свой код, но есть так же решения, которые можно внедрить на свой сайт.

    Совет: активация отображения всех ошибок в PHP

    При поднятии PHP проекта на новом рабочем окружении могут возникнуть ошибки отображение которых изначально скрыто базовыми настройками. Это можно исправить, прописав несколько команд.

    Источник

Оцените статью