1 | <?php |
||
12 | class FixedBlock |
||
13 | { |
||
14 | /** |
||
15 | * Default permission (octal) that will be used in created memory blocks. |
||
16 | * |
||
17 | * @var int |
||
18 | */ |
||
19 | const DEFAULT_PERMISSION = 0644; |
||
20 | |||
21 | /** |
||
22 | * Shared memory block id returned by shmop_open. |
||
23 | * |
||
24 | * @var int |
||
25 | */ |
||
26 | protected $shmid; |
||
27 | |||
28 | /** |
||
29 | * Shared memory block instantiation. |
||
30 | * |
||
31 | * In the constructor we'll check if the block we're going to manipulate |
||
32 | * already exists or needs to be created. If it exists, let's open it. |
||
33 | * |
||
34 | * @param string $id |
||
35 | * @param int $size |
||
36 | * @param int $perms |
||
37 | */ |
||
38 | 4 | public function __construct($id, $size, $perms = self::DEFAULT_PERMISSION) |
|
39 | { |
||
40 | 4 | if ($this->exists($id)) { |
|
41 | 1 | $this->shmid = shmop_open($id, 'w', $perms, $size); |
|
42 | 1 | } else { |
|
43 | 4 | $this->shmid = shmop_open($id, 'c', $perms, $size); |
|
44 | } |
||
45 | 4 | } |
|
46 | |||
47 | /** |
||
48 | * Checks if a shared memory block with the provided id exists or not. |
||
49 | * |
||
50 | * @param string $id |
||
51 | * |
||
52 | * @return bool |
||
53 | */ |
||
54 | 4 | public function exists($id) |
|
55 | { |
||
56 | 4 | return (bool) @shmop_open($id, 'a', 0, 0); |
|
57 | } |
||
58 | |||
59 | /** |
||
60 | * Writes on a shared memory block. |
||
61 | * |
||
62 | * @param string $data |
||
63 | * |
||
64 | * @return bool |
||
65 | */ |
||
66 | 3 | public function write($data) |
|
67 | { |
||
68 | 3 | return shmop_write($this->shmid, $data, 0) !== false; |
|
69 | } |
||
70 | |||
71 | /** |
||
72 | * Reads from a shared memory block. |
||
73 | * |
||
74 | * @return string |
||
75 | */ |
||
76 | 4 | public function read() |
|
77 | { |
||
78 | 4 | return trim(shmop_read($this->shmid, 0, shmop_size($this->shmid))); |
|
79 | } |
||
80 | |||
81 | /** |
||
82 | * Mark a shared memory block for deletion. |
||
83 | * |
||
84 | * @return bool |
||
85 | */ |
||
86 | 1 | public function delete() |
|
87 | { |
||
88 | /* |
||
89 | * Bug fix |
||
90 | * @link https://bugs.php.net/bug.php?id=71921 |
||
91 | */ |
||
92 | 1 | shmop_write($this->shmid, str_pad('', shmop_size($this->shmid), ' '), 0); |
|
93 | |||
94 | 1 | return shmop_delete($this->shmid); |
|
95 | } |
||
96 | |||
97 | /** |
||
98 | * Closes the shared memory block and stops manipulation. |
||
99 | */ |
||
100 | 2 | public function __destruct() |
|
104 | } |
||
105 |