PHP 进程间内存共享

启用php的共享内存:

1).windows下,php.ini中取消 ;extension=php_shmop.dll 这行的行首分号,加载shmop扩展。
2) .linux/unix下,重新编译php,加入--enable--shmop 选项。

Shared Memory 的函数解释如下:


测试代码如下:
 1<?php
 2/*
 3 * @文件: create.php
 4 * @功能:将全局变量写入共享内存中
 5*/
 6
 7//定义全局变量
 8$super = "hello world";
 9
10//申请100字节共享内存空间
11$shm_id = shmop_open(0xff3, "c", 0644, 100);
12if (!$shm_id) {
13    echo "申请空间失败<br>";
14}
15
16//内容写入共享内存空间
17if (shmop_write($shm_id, $super, 0)) {
18    echo "全局变量已经写入共享内存<br>";
19}
20else {
21    echo "写入共享内存失败<br>";
22}
23
24//关闭共享内存空间
25shmop_close($shm_id);
26?>
 1<?php
 2/*
 3 * @文件: read.php
 4 * @功能:读取共享内存中的内容
 5*/
 6
 7//读100字节共享内存空间
 8$shm_id = shmop_open(0xff3, "a", 0644, 100);
 9
10//获取共享内存空间中的前11个字节的内容
11//create.php中 $super 变量长度为11
12$share = shmop_read($shm_id, 0, 11);
13
14echo $share;
15
16//关闭
17shmop_close($shm_id);
18?>

测试方法:浏览过 create.php 页面,只要 HTTP 服务不关,以后每打开 read.php 就能读取到共享内存中的 "hello world"。还有一种测试办法,在 create.php 后加个 while(true){} 让脚本不会退出,第一个 dos 窗口执行 php create.php,然后在别的窗口中执行 php read.php 就能在控制台下输出 "hello world"。

参考:http://blog.csdn.net/johnpanq/archive/2005/12/29/564818.aspx

永久链接 https://yanbin.blog/php-share-memory-cross-proces/, 来自 隔叶黄莺 Yanbin's Blog
[版权声明] 本文采用 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 进行许可。