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.shmop_open
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
shmop_open
Референца за `function.shmop-open.php` со подобрена типографија и навигација.
shmop_open
(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)
shmop_open — Креирај или отвори блок за споделена меморија
= NULL
int
$key,string
$mode,int
$permissions,int
$size): Функции за споделена меморија|false
shmop_open() може да креира или отвори блок за споделена меморија.
Параметри
key- Системски ID за блокот за споделена меморија. Може да се помине како децимален или хексадецимален.
mode-
Знаменцата што можете да ги користите:
- "a" за пристап (поставува SHM_RDONLY за shmat) користете го ова знаменце кога треба да отворите постоечки сегмент за споделена меморија само за читање
- "c" за креирање (поставува IPC_CREATE) користете го ова знаменце кога треба да креирате нов сегмент за споделена меморија или ако постои сегмент со истиот клуч, обидете се да го отворите за читање и пишување
- "w" за пристап за читање и пишување користете го ова знаменце кога треба да читате и пишувате во сегмент за споделена меморија, користете го ова знаменце во повеќето случаи.
- "n" креирај нов мемориски сегмент (поставува IPC_CREATE|IPC_EXCL) користете го ова знаменце кога сакате да креирате нов сегмент за споделена меморија, но ако веќе постои еден со истото знаменце, откажете. Ова е корисно за безбедносни цели, користејќи го ова можете да спречите експлоатации на тркачки состојби.
permissions-
Дозволите што сакате да ги доделите на вашиот мемориски сегмент, тие се исти како дозволите за датотека. Дозволите треба да се поминат во октален облик, како на пример
0644 size- Големината на блокот за споделена меморија што сакате да го креирате во бајти
Забелешка: Забелешка: 3-тото и 4-тото треба да се внесат како 0 ако отворате постоечки мемориски сегмент.
Вратени вредности
На успех shmop_open() ќе врати Функции за споделена меморија инстанца што можете да ја користите за пристап до сегментот за споделена меморија што сте го креирале. false се враќа при неуспех.
Errors/Exceptions
Враќа mode е неважечки, или size е помал или еднаков на нула, а ValueError се фрла. При други неуспеси, E_WARNING се емитува.
Дневник на промени
| Верзија | = NULL |
|---|---|
| 8.0.0 | При успех, оваа функција враќа Функции за споделена меморија инстанца сега; претходно, а resource . |
| 8.0.0 |
Враќа mode е неважечки, или size е помал или еднаков на нула, а ValueError се фрла; претходно E_WARNING беше емитувано наместо тоа, а функцијата врати false.
|
Примери
Пример #1 Креирај нов блок за споделена меморија
<?php
$shm_key = ftok(__FILE__, 't');
$shm_id = shmop_open($shm_key, "c", 0644, 100);
?>Овој пример отвори блок за споделена меморија со системски ID вратен од ftok().
Види Исто така
- shmop_close() Затвори блок за споделена меморија
- shmop_delete() Избриши блок за споделена меморија
Белешки од корисници 9 белешки
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 :)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 0One 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:1I'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.");
?>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.=== 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
}
?>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.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";
}