当前位置:首页 > Web开发 > 正文

点击官方文档地址: ftok (PHP 4 = 4.2.0

2024-03-31 Web开发

这里会用到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 $key = ftok(__DIR__, ‘p‘); $queue = msg_get_queue($key); echo("queue_key:" . $key . PHP_EOL); $i = 0;
//这里是梗阻模式,不会因为while(true)而陷入死循环,内存爆满的情况
while(true) { msg_receive($queue, 0, $msg_type, 1024, $message, false, 0); echo("i: " . $i . ‘, message: ‘ .$message);

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

开始执行

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

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

使用PHP的ftok()函数实现基于linux下系统级进程间动静通信demon(动静行列队伍模式)

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/30972.html