PHP.mk документација

sem_get

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.sem-get.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.sem-get.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
sem_get

Референца за `function.sem-get.php` со подобрена типографија и навигација.

function.sem-get.php

sem_get

(PHP 4, PHP 5, PHP 7, PHP 8)

sem_getДобијте ID на семафор

= NULL

sem_get(
         int $key,
         int $max_acquire = 1,
         int $permissions = 0666,
         bool $auto_release = true
): SysvSemaphore|false

sem_get() враќа ID што може да се користи за пристап до семафорот System V со дадениот key.

Втор повик на sem_get() за истиот клуч ќе врати различен идентификатор на семафор, но двата идентификатори пристапуваат до истиот основен семафор.

Враќа key is 0, нов приватен семафор се создава за секој повик до sem_get().

Параметри

key
max_acquire
Бројот на процеси што можат истовремено да го стекнат семафорот е поставен на max_acquire.
permissions
Дозволите за семафор. Всушност, оваа вредност се поставува само ако процесот открие дека е единствениот процес што моментално е поврзан со семафорот.
auto_release
Определува дали семафорот автоматски ќе се ослободи при исклучување на барањето.

Вратени вредности

Враќа позитивен идентификатор на семафор при успех, или false при грешка.

Дневник на промени

Верзија = NULL
8.0.0 При успех, оваа функција враќа SysvSemaphore инстанца сега; претходно, а resource .
8.0.0 Типот на auto_release е променето од int to bool.

Белешки

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Кога користите sem_get() за пристап до семафор создаден надвор од PHP, имајте предвид дека семафорот мора да биде создаден како сет од 3 семафори (на пример, со специфицирање на 3 како nsems параметар при повикување на C semget() функција), инаку PHP нема да може да пристапи до семафорот.

Види Исто така

  • sem_acquire() - Стекни семафор
  • sem_release() - Ослободи семафор
  • ftok() - Претвора патека и идентификатор на проект во клучен IPC на System V

Белешки од корисници 9 белешки

Ден Ист
пред 5 години
Note that the default permissions parameter is octal!  Thus the default of 0666 is NOT the same as 666, or 0x666.

If you specify the permission as decimal 666 then you end up with permissions that prevent the semaphore from being read.  The symptom is that you can only sem_get it once, and subsequent sem_get will fail (until you ipcrm or sem_remove it and delete it entirely).

Thus these are all equivalent to the default:
sem_get ( 123, 1, 0666) 
sem_get ( 123, 1, 438) 
sem_get ( 123, 1, 0x1b6)

Most PHP developers (myself included) work with octal numbers so infrequently that the number 0666 can easily be mistaken as 666 or maybe 0x666.
soger
пред 14 години
Actually it looks like the semaphore is automatically released not on request shutdown but when the variable you store it's resource ID is freed. That is a very big difference.
kakkau на grr точка la
пред 9 години
It is possible to create an "infinite" amount of semaphores when setting $key = 0.

Run sem_get multiple times
php > sem_get(0,0);

and check the output of
$ ipcs -s

------ Semaphore Arrays --------
key        semid      owner      perms      nsems     
0x00000000 1277952    user       666        3         
0x00000000 1310721    user       666        3

As you can see there were multiple semaphores set up with key 0.
For any other integer sem_get works as expected. It returns another resource id pointing to the semaphore previously created and does not create another semaphore.
kakkau на grr точка la
пред 10 години
For those that encounter strange behavior in using sem_acquire() on resources generated by sem_get(). Have a look at  sem_get()'s 4th parameter auto_release. It allows multiple acquisitions through reassignments to resource variables.

./multi.acquire.php
<?php
class Sem {
  private $key = null;
  private $res = null;
  public function __construct() {
    $this->key = ftok(".",".");
    $this->set_res();
    $this->acquire();
  }
  public function set_res() {
    // 4th parameter auto_released is 1 by default
    $this->res = sem_get($this->key, 1, 0600, 1);
  }
  public function acquire() {
    echo "acquired='".sem_acquire($this->res,true)."'\n";
  }
}

$s = new Sem();
$s->set_res();
$s->acquire();

?>

$ php multi.acquire.php
acquired='1'
acquired='1'

To avoid reacquiring by default set sem_get()'s parameter auto_release to 0 or check if your resource variable is already set, e.g. by using is_null().
Мајкл З.
пред 14 години
Watch out when you use fileinode() to get a unique semaphore key (as suggested in some comment on this or a related function) in conjunction with version control software: It seems, for example, SVN will change the inode. Using such a file will leave you with your mutex not working reliably and your system's semaphore pool being filled until further attempts to get a semaphore will fail. Use ipcs and ipcrm commands from linux-util-ng (on most distros probably) to examine/fix related problems.
neofutur
19 години пред
with gentoo php5 you will need to add the USE flag :
sysvipc

see :
 http://forums.gentoo.org/viewtopic-t-464175-highlight-semget+php.html

and also :
 http://overlays.gentoo.org/proj/php/
joeldg на listbid.com
пред 22 години
<?
// thanks to
// http://www.ecst.csuchico.edu/~beej/guide/ipc/shmem.html
$SHM_KEY = ftok("/home/joeldg/homeymail/shmtest.php", 'R');
$shmid = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$data = shm_attach($shmid, 1024);

$data = "test";
printf("shared contents: %s\n", $data);

shm_detach($data);
?>
joeldg НА listbid.com
пред 22 години
Heh, actually the above comment I added is not technically correct, it was more of an idea to display the function.

$SHM_KEY = ftok("/home/joeldg/homeymail/shmtest.php", 'R');
$shmid = sem_get($SHM_KEY, 1024, 0644 | IPC_CREAT);
$data = shm_attach($shmid, 1024);
// we now have our shm segment

// lets place a variable in there
shm_put_var ($data, $inmem, "test");
// now lets get it back. we could be in a forked process and still have
// access to this variable.
printf("shared contents: %s\n", shm_get_var($data, $inmem));

shm_detach($data);
ein на anti-logic точка com
пред 18 години
Be aware that there is no way to ensure that you have exclusive access to a lock, despite setting max_acquire=1.

In example,
<?
$fp = sem_get(fileinode('lock_file', 100);
sem_acquire($fp);

$fp2 = sem_get(fileinode('lock_file', 1);
sem_acquire($fp2);
?>

This will not block on the second sem_aquire.  Therefore, if you have functions or processes that utilize shared locks (>1 max_acquire) you will still need to provide a seperate lock mechanism (ie flock) for write access, making the sem_ functions useless.

Some more info, in flock, each reference to the lock file has it's own options (can be shared exclusive blocking non blocking etc), but apparently php's sem functions only support these options per semaphore, not per semaphore-reference.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.