zoukankan      html  css  js  c++  java
  • 使用PHP的ftok()函数实现基于linux下系统级进程间消息通信demo(消息队列模式)

    这里会用到ftok()函数,点击官方文档地址:

    ftok

    (PHP 4 >= 4.2.0, PHP 5, PHP 7)

    ftok — Convert a pathname and a project identifier to a System V IPC key

    说明

    ftok ( string $pathname , string $proj ) : int

    The function converts the pathname of an existing accessible file and a project identifier into an integer for use with for example shmop_open() and other System V IPC keys.

     以上解释:大意$pathname是文件名(需要确保文件可读), $proj是自己定义的标识,得到的就是一个可访问的路径名和一个整数标识符转换成一个key_t值。

    新建msg_send.php

    <?php
    
    $key = ftok(__DIR__, 'p');
    
    echo($key . PHP_EOL);
    
    #队列资源句柄
    $queue = msg_get_queue($key);
    //var_dump($queue);
    
    #队列状态信息
    $info = msg_stat_queue($queue);
    //var_export($info);
    
    $i = 0;
    
    while($i++ < 10)
    {
        msg_send($queue, 1, '吃饭了吗? ' . $i , false, false);
    }

    同级目录新建msg_receive.php

    <?php

    $index = $argv[1];
    $key = ftok(__DIR__, 'p'); $queue = msg_get_queue($key); echo("queue_key:" . $key . PHP_EOL);
    //这里是阻塞模式,不会因为while(true)而陷入死循环,内存爆满的情况
    while(true) { msg_receive($queue, 0, $msg_type, 1024, $message, false, 0); echo('index: ' . $index . ', message: ' .$message);

    sleep(2);//增加耗时方便展示演示效果 }

     开始执行

    [root@guangzhou msg]# php msg_send.php
    1879117732
    #为了增加演示效果,开了三个窗口同时运行msg_receive.php,分别传参one, two, three
    [root@guangzhou msg]# php msg_receive.php one
    queue_key:1879117732
    index: one, message: 吃饭了吗? 1
    index: one, message: 吃饭了吗? 2
    index: one, message: 吃饭了吗? 5
    index: one, message: 吃饭了吗? 8 [root@guangzhou msg]# php msg_receive.php two queue_key:1879117732
    index: two, message: 吃饭了吗? 3
    index: two, message: 吃饭了吗? 6
    index: two, message: 吃饭了吗? 9 [root@guangzhou msg]# php msg_receive.php three queue_key:1879117732
    index: three, message: 吃饭了吗? 4
    index: three, message: 吃饭了吗? 7
    index: three, message: 吃饭了吗? 10 #通过脚本输出可以看到类似redis队列读取的效果
    #最后如果不需要可以销毁队列msg_remove_queue($queue)

    注意:如果脚本运行期间ftok()函数计算数值发生改变,更改前后读取的队列名可能不一致,比如文件执行前被创建,执行中被删除或重新创建或文件内容本身变动,两次得到的ftok可能会不一样。 

    系统关机后存在队列中的数据会被销毁,重启无法恢复。

  • 相关阅读:
    [STL][C++]MAP
    [原创]南水之源A*(A-Star)算法
    php+mysql模糊查询功能
    php中如何传递Session ID
    初识jsonp
    跨站脚本攻击XSS
    XSS危害——session劫持
    PHP中获取当前页面的完整URL
    smarty获得当前url的方法分享
    表空间的管理方式有哪几种,各有什么优劣?
  • 原文地址:https://www.cnblogs.com/wscsq789/p/12234953.html
Copyright © 2011-2022 走看看