当前位置:Gxlcms > PHP教程 > phpshmop_open的有关问题

phpshmop_open的有关问题

时间:2021-07-01 10:21:17 帮助过:4人阅读

php shmop_open的问题
PHP code
  1. <!--
  2. Code highlighting produced by Actipro CodeHighlighter (freeware)
  3. http://www.CodeHighlighter.com/
  4. -->
  5. <!--?php
  6. $arr=array();
  7. function application($key,$value="")
  8. {
  9. global $arr;
  10. if($value=="")
  11. {
  12. $shm_id = @shmop_open(12345, "a", 0644,100);
  13. }else{
  14. @$shm_id = shmop_open(12345, "c",0,0);
  15. if(!$shm_id)
  16. {
  17. $shm_id=shmop_open(12345,"c",0644,100);
  18. }
  19. }
  20. @$byte=shmop_read($shm_id,0,1024*1024);
  21. if(!$byte){
  22. return "";
  23. }else{
  24. if($byte!=""){
  25. $arr=unserialize($byte);
  26. }else{
  27. return "";
  28. }
  29. }
  30. if($value=="")//取值
  31. {
  32. shmop_close($shm_id);
  33. if(array_key_exists($key,$arr))
  34. {
  35. return $arr[$key];
  36. }
  37. return "";
  38. }else{
  39. $arr[$key]=$value;
  40. shmop_write($shm_id,serialize($arr),0);
  41. shmop_close($shm_id);
  42. }
  43. }
  44. ?-->


我在php中实现asp中的application对象的功能
目前的问题是在同一个http请求之中,执行了application("a","1"),那么application("a")会返回1,上面这个函数是正常的
但如果开始第二个请求了,application("a")就取不到值了
问题出在哪儿啊?


------解决方案--------------------
shmop_open(12345, "a", 0644,100);
表示最大可能的空间(字节数)
而你 shmop_read($shm_id,0,1024*1024);
读取时就越界了,这就是所谓的内存溢出
------解决方案--------------------
一般可以这样写
PHP code
  1. $p = new shared;
  2. //$p->a = 'abcd';
  3. //$p->b = 1234;
  4. print_r($p->_all);
  5. echo $p->b;
  6. class shared {
  7. private $shm_id;
  8. private $shm_key = 0xff3;
  9. private $shm_size = 1024;
  10. function __construct() {
  11. $this->shm_id = shmop_open($this->shm_key, "c", 0644, $this->shm_size) or die('申请失败');
  12. }
  13. function __get($name) {
  14. $buf = shmop_read($this->shm_id, 0, $this->shm_size);
  15. $buf = unserialize(trim($buf));
  16. if($name == '_all') return $buf;
  17. return isset($buf[$name]) ? $buf[$name] : false;
  18. }
  19. function __set($name, $value) {
  20. $buf = shmop_read($this->shm_id, 0, $this->shm_size);
  21. $buf = unserialize(trim($buf));
  22. $buf[$name] = $value;
  23. $buf = serialize($buf);
  24. if(strlen($buf) >= $this->shm_size) die('空间不足');
  25. shmop_write($this->shm_id, $buf, 0) or die('写入失败');
  26. }
  27. }
  28. <br><font color="#e78608">------解决方案--------------------</font><br>和你上一个帖子一样,讨论是在基于 php_shmop.dll 扩展的<br><br>linux 中有另外的方法,但原理是一样的<br>php_shmop 也可以在 linux 中编译,但他却是为 window 设计的<br>
  29. <br><font color="#e78608">------解决方案--------------------</font><br>我就明着告诉你,你这个问题大了.<br><br>共享内存区需要加锁操作, php没法设置进程共享的mutex, 你可以同样适用一个system v 的sem二值信号量来做锁.

人气教程排行