With shmop_read, you probably get a "\0" - padded string.
$zero_padded = shmop_read($shm_seg, 0, 128);
$usable_string = rtrim($zero_padded, "\0");
(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)
shmop_read — Read data from shared memory block
shmop_read() will read a string from shared memory block.
shmop
The shared memory block identifier created by shmop_open()
offset
Offset from which to start reading
size
The number of bytes to read.
0
reads shmop_size($shmid) - $start
bytes.
Returns the data 或者在失败时返回 false
.
版本 | 说明 |
---|---|
8.0.0 |
shmop expects a Shmop
instance now; previously, a resource was expected.
|
Example #1 Reading shared memory block
<?php
$shm_data = shmop_read($shm_id, 0, 50);
?>
This example will read 50 bytes from shared memory block and place the data
inside $shm_data
.
With shmop_read, you probably get a "\0" - padded string.
$zero_padded = shmop_read($shm_seg, 0, 128);
$usable_string = rtrim($zero_padded, "\0");
You should always serialize data written in shared memory.
And when you are reading data you should always unserialize.
<?php
$data = 'test';
$shm_bytes_written = shmop_write($shm_id, serialize($data), 0);
$shm_data = unserialize(shmop_read($shm_id, 0, $shm_bytes_written));
?>
shmop_read() reads and returns the whole memory segment's data. This is not useful if you're just working with strings. If you need to read a string from shared memory, call str_from_mem() on the result of shmop_read(). Similarly when writing strings to memory (instead of binary data), null terminate your strings with str_to_nts() before passing the value on to shmop_write().
function str_to_nts($value) {
return "$value\0";
}
function str_from_mem(&$value) {
$i = strpos($value, "\0");
if ($i === false) {
return $value;
}
$result = substr($value, 0, $i);
return $result;
}
Also you can use the shmop_size() function to determine the block size.
When i need to read the whole string at that shm pointer, setting the count parameter to zero (0) seems work for me.