CakeFest 2024: The Official CakePHP Conference

shmop_open

(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)

shmop_openРезервирование или использование блока разделяемой памяти

Описание

shmop_open(
    int $key,
    string $mode,
    int $permissions,
    int $size
): Shmop|false

shmop_open() резервирует или использует существующий блок разделяемой памяти.

Список параметров

key

Системный идентификатор блока разделяемой памяти. Может быть задан в десятичной или шестнадцатеричной кодировке.

mode

Доступные для использования флаги:

  • "a" для доступа (устанавливает флаг SHM_RDONLY) Следует применять этот флаг, когда необходимо использовать ранее зарезервированный участок разделяемой памяти, уже содержащий какие-либо данные. В этом случае доступ возможен только для операций чтения.
  • "c" для резервирования (устанавливает флаг IPC_CREATE) Следует применять этот флаг для создания нового зарезервированного участка разделяемой памяти. Если участок памяти с таким идентификатором уже существует, выполняется попытка доступа к нему для последующих операций чтения и записи.
  • "w" для выполнения операций чтения и записи Следует применять этот флаг для чтения и записи данных, хранимых в разделяемой памяти. Данный флаг используется в большинстве случаев.
  • "n" для создания в памяти нового сегмента (устанавливает флаг IPC_CREATE|IPC_EXCL) Следует применять этот флаг для создания нового сегмента в разделяемой памяти, но если сегмент уже существует с тем же флагом, происходит отказ. Это полезно в целях безопасности, т.к. позволяет избежать ошибок синхронизации (Race condition exploits).

permissions

Права доступа к участку памяти такие же, как к обычному файлу. Их можно указывать в восьмеричном виде, например 0644.

size

Размер резервируемого блока в разделяемой памяти в байтах

Замечание:

Обратите внимание: третий и четвёртый параметры должны быть указаны как 0, если необходимо получить доступ к существующему участку памяти.

Возвращаемые значения

В случае успешного выполнения shmop_open() возвращает экземпляр Shmop, который может быть в дальнейшем использован для доступа к зарезервированному участку памяти. В случае возникновения ошибки возвращает false.

Ошибки

Если параметр mode указан некорректно или параметр size меньше или равен нулю, выдаётся ошибка ValueError. В случае возникновения других ошибок выдаётся ошибка уровня E_WARNING.

Список изменений

Версия Описание
8.0.0 В случае успешного выполнения возвращается экземпляр Shmop; ранее возвращался ресурс (resource).
8.0.0 Если параметр mode указан некорректно или параметр size меньше или равен нулю, выдаётся ошибка ValueError. previously E_WARNING was emitted instead, ранее вместо этого выдавалась ошибка уровня E_WARNING и функция возвращала false.

Примеры

Пример #1 Резервирование участка разделяемой памяти

<?php
$shm_key
= ftok(__FILE__, 't');
$shm_id = shmop_open($shm_key, "c", 0644, 100);
?>

В приведённом примере выполняется доступ к блоку с идентификатором, возвращаемым функцией ftok().

Смотрите также

  • shmop_close() - Закрытие блока разделяемой памяти
  • shmop_delete() - Удаление блока разделяемой памяти

add a note

User Contributed Notes 9 notes

up
5
kakkau at grr dot la
7 years ago
On *nix systems shmop_open is able to create an "infinite" amount of segments when setting $key = 0.

After executing the following command twice in an interactive shell
php > $res = shmop_open(0,"n",0600,1024);

list the memory segments currently present
$ ipcs -m

------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x00000000 2293762 user 600 1024 0
0x00000000 2326531 user 600 1024 0

For any integer <> 0 in conjunction with the flag "n" shmop_open works like documented. It fails.
up
4
daniele_dll at yahoo dot it
20 years ago
There is a little ftok function. This function isn't included into php for windows so i've grabbed it directly from linux glibc 2.3.2 source code. I hope that this can be useful.
There is the code:

<?php
function ftok($pathname, $proj_id) {
$st = @stat($pathname);
if (!
$st) {
return -
1;
}

$key = sprintf("%u", (($st['ino'] & 0xffff) | (($st['dev'] & 0xff) << 16) | (($proj_id & 0xff) << 24)));
return
$key;
}

echo
ftok($_SERVER["SCRIPT_FILENAME"], 250);
?>

sorry for my english :)
up
1
Craig Manley
19 years ago
To: macmaster at pobox dot com:

To clear up some new confusion: you said the shm key is 8 bytes long. As far as I know it's 4 bytes (32bits).
Check out the output of ipcs on Linux below to see what I mean.

------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x6e6a694d 65538 mijnbel 644 65536 0
0x326e794d 98307 mijnbel 644 65536 0
0x62417347 131076 smsklap 644 65536 0
up
1
erelsgl at gmail dot com
16 years ago
=== Checking if a shared memory exists ===
The solution provided by Mitchell_Shnier at ieee dot orgZ doesn't work on my computer - I get a warning "Invalid flag ac".

In order to check if a shared-memory exists, you just have to open it with the "a" or "w" flag, while hiding the warnings using the "@" operator:
<?php
@$shid = shmop_open($systemId, "a", 0666, 0);
if (!empty(
$shid)) {
...
shared memory exists
} else {
...
shared memory doesn't exist
}
?>
up
1
Filippo Fadda
9 years ago
I'm having the same issue affecting XP and described below, on Mac OS X Lion.

To solve it, use before 'a' flag, then 'n'. Avoid 'c' flag.

<?php
$str
= 'Hello World';

shm_key = ftok($_SERVER['PHP_SELF']);

if (@
$shm_id = shmop_open($shm_key, 'a', 0644, 0))
shmop_delete($shm_id);

$shm_id = shmop_open($shm_key, 'n', 0644, strlen($str));

if (
$shmId) {
shmop_write($shmId, $str, 0);
shmop_close($shmId);
}
else
throw new
RuntimeException("Couldn't create shared memory segment.");
?>
up
0
kakkau at grr dot la
6 years ago
One is not able to reconnect to a segment with key 0. For any other key (e.g. 1) the flags just work fine.

php > $soid = shmop_open(0,"n",0600,10);
php > $soid = shmop_open(0,"w",0600,10);
PHP Warning: shmop_open(): unable to attach or create shared memory segment 'Invalid argument' in php shell code on line 1
PHP Stack trace:
PHP 1. {main}() php shell code:0
PHP 2. shmop_open(0, 'w', 384, 10) php shell code:1
up
0
thanks at forthefish dot com
10 years ago
These shared memory functions are kind of silly on Windows where sem_get() and friends nor any sort of synchronization object is available (as of PHP 5.5.5) to perform proper locking prior to access. A core PHP dev needs to write some wrappers for sem_get() for Windows as they did for shmop to really round out this feature.

The implementation of shmop for Windows is pretty slick - the author basically ported variations of POSIX functions to Windows equivalent prototypes.
up
0
Chris Petersen
20 years ago
Be warned that if you try to shmop_open with a key set to zero, shmop_open will seemingly work, and you can write to it, but you will not be able to read from it or delete it. If you're not careful, you can continue doing this - creating more and more shared memory blocks at "zero" until eventually you WILL start getting errors saying that php can't access or create the shared memory block, and you will have to restart your machine to free up all of those "zero" blocks.
up
-1
Colin Paterson
8 years ago
If you are running your main script as say user "root" but need to open a Shared Memory Segment as another user (from your main script) such as say "www-data" then this works:

exec("sudo -u www-data php -r 'shmop_open(0xee4, "c", 0770, 100);'"); //Create Shared Memory segment as USER www-data

$SharedMemorySegment = shmop_open(0xee4, "c", 0770, 100);
if (!$SharedMemorySegment) {
echo "Couldn't create shared memory segment\n";
}
To Top