php-ipc/src/Shm/SharedMemoryBlock.php

99 lines
2.0 KiB
PHP

<?php
namespace NoccyLabs\Ipc\Shm;
use NoccyLabs\Ipc\Key\KeyInterface;
/**
* A block of shared memory that can be read and write like a string buffer
*
*
*/
class SharedMemoryBlock
{
const FLAG_ACCESS = "a";
const FLAG_CREATE = "c";
const FLAG_WRITE = "w";
const FLAG_NEW = "n";
protected $resource;
/**
* Constructor
*
* @param KeyInterface $key
* @param string $flags
* @param integer $memsize
* @param integer $perm
*/
public function __construct(KeyInterface $key, string $flags, int $memsize, int $perm = 0666)
{
if (!($shm_resource = shmop_open($key->getKey(), $flags, $perm, $memsize))) {
throw new \RuntimeException("Unable to attach shm resource {$key}");
}
$this->resource = $shm_resource;
}
/**
* Destructor
*/
public function __destruct()
{
if (!$this->resource) {
return;
}
shmop_close($this->resource);
}
/**
* Destroy the memory block
*
* @return void
*/
public function destroy()
{
shmop_delete($this->resource);
shmop_close($this->resource);
$this->resource = null;
}
/**
* Read bytes from the shared block
*
* @param integer $length
* @param integer $offset
* @return mixed
*/
public function read($length=0, $offset=0)
{
if ($length == 0) {
$length = shmop_size($this->resource) - $offset;
}
return shmop_read($this->resource, $offset, $length);
}
/**
* Write bytes to the shared block
*
* @param mixed $data
* @param integer $offset
* @return integer
*/
public function write($data, $offset=0):int
{
return shmop_write($this->resource, $data, $offset);
}
/**
* Get the size of the memory block
*
* @return integer
*/
public function getSize():int
{
return shmop_size($this->resource);
}
}