Initial commit
This commit is contained in:
94
src/Shm/SharedMemory.php
Normal file
94
src/Shm/SharedMemory.php
Normal file
@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace NoccyLabs\Ipc\Shm;
|
||||
|
||||
use NoccyLabs\Ipc\Key\KeyInterface;
|
||||
|
||||
/**
|
||||
* Shared memory segment
|
||||
*/
|
||||
class SharedMemory implements \ArrayAccess
|
||||
{
|
||||
|
||||
protected $resource;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param KeyInterface $key
|
||||
* @param integer $memsize
|
||||
* @param integer $perm
|
||||
*/
|
||||
public function __construct(KeyInterface $key, int $memsize = 64000, int $perm = 0666)
|
||||
{
|
||||
if (!($shm_resource = shm_attach($key->getKey(), $memsize, $perm))) {
|
||||
throw new \RuntimeException("Unable to attach shm resource {$key}");
|
||||
}
|
||||
|
||||
$this->resource = $shm_resource;
|
||||
}
|
||||
|
||||
/**
|
||||
* Destructor
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
shm_detach($this->resource);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy the shm segment
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function destroy()
|
||||
{
|
||||
shm_remove($this->resource);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @param int $offset
|
||||
* @return void
|
||||
*/
|
||||
public function offsetExists($offset)
|
||||
{
|
||||
return shm_has_var($this->resource, $offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @param int $offset
|
||||
* @return mixed
|
||||
*/
|
||||
public function offsetGet($offset)
|
||||
{
|
||||
return shm_has_var($this->resource, $offset)?shm_get_var($this->resource, $offset):null;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @param int $offset
|
||||
* @param mixed $value
|
||||
* @return void
|
||||
*/
|
||||
public function offsetSet($offset, $value)
|
||||
{
|
||||
shm_put_var($this->resource, $offset, $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @param int $offset
|
||||
* @return void
|
||||
*/
|
||||
public function offsetUnset($offset)
|
||||
{
|
||||
shm_remove_var($this->resource, $offset);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user