<?php /** * Description: * Shared memory access * * History: * Created by Moky @ 2009-07-28 */ /** Samples: include_once('include/lib/shm.php'); $my_shm = new SHM(0x9527001, 1024*10); // create $pos = 0; $str = 'Hey girl!'; $my_shm->write($pos, $str); // write $len = strlen($str); echo $my_shm->read($pos, $len); // read */ class SHM { var $shm_id; var $shm_key; var $shm_size; /** * construct */ function SHM($key, $size) { $this->init($key, $size); } /** * destruct */ function __destruct() { $this->close(); } function init($key, $size, $perm = 0644) { $shm_id = $this->getId($key); if (!$shm_id) { // shm not exists, create it $shm_id = $this->create($key, $size, $perm); if (!$shm_id) { // create failed return -1; } } if (shmop_size($shm_id) != $size) { // create error return -2; } $this->shm_id = $shm_id; $this->shm_key = $key; $this->shm_size = $size; return $shm_id; } function write($pos, $str) { // check handler $shm_id = $this->getId(); if (!$shm_id) return -1; // check range if ($pos < 0) return -2; $shm_size = $this->shm_size; if ($pos + strlen($str) >= $shm_size) return -2; // write $len = shmop_write($shm_id, $str, $pos); return $len; } function read($pos, $len) { // check handler $shm_id = $this->getId(); if (!$shm_id) return -1; // check range if ($pos < 0) return -2; $shm_size = $this->shm_size; if ($pos + $len >= $shm_size) return -2; // read $str = shmop_read($shm_id, $pos, $len); return $str; } function delete($key = NULL) { $shm_id = getId($key); if (!$shm_id) { return -1; } if (!shmop_delete($shm_id)) { return -1; } return 0; } /// function getId($key = NULL) { return !$key ? $this->shm_id : $this->create($key, 0, 0); } function getKey() { return $this->shm_key; } function getSize($key = NULL) { $shm_id = $this->getId($key); if (!$shm_id) return -1; return shmop_size($shm_id); } function create($key, $size, $perm) { return shmop_open($key, 'c', $perm, $size); } function close($key = NULL) { $shm_id = $this->getId($key); if (!$shm_id) return -1; return shmop_close($shm_id); } } // end of class SHM ?>