How to use PHP shmop to create and manipulate shared memory segments, using them to store data that can be used by other applications.
1. Create a memory segment
A shared memory function is similar to a file manipulation function, but there is no need to process a stream and you will process a shared memory access ID. The first example isthe Shmop open function, which allows you to open an existing memory segment or create a new memory segment. This function is very similar to the classic fopen function, which opens a stream for file operations and returns a resource for use by other functions that want to read or write to the open stream. Let's take a look atthe usage of SHMOP open:
<?php $key = ftok(__FILE__, ‘h‘);$mode = ‘c‘;$permissions = 0644;$size = 1024;$shmid = shmop_open($key, $mode, $permissions, $size);?>
First parameter ($key):
A key value must be specified when the system establishes an IPC communication (Message Queuing, semaphores, and shared memory). Typically, this key value is obtained through the Ftok function, * *key is an identity that we logically represent shared memory segments. Different processes can share the same segment of a bucket simply by selecting the same key value.
Second parameter ($mode):
Access mode, which resembles the fopen access mode, has the following several
- Mode "A", which allows you to access read-only memory segments
- Mode "W", which allows you to access read-write memory segments
- The mode "C", which creates a new memory segment, or if the memory segment already exists, attempts to open it for read-write * mode "n", it creates a new memory segment, fails if the memory segment already exists, returns false, and accompanies warning:unable to attach or Create Shared memory segment
The third parameter ($permissions):
The permissions for the memory segment. You must provide an octal value here that resembles the operating permissions of the UNIX operating system files and directories.
Fourth parameter ($size):
The size of the memory segment, in bytes. Before writing a memory segment, you must allocate the appropriate number of bytes on top of it.
return Result:
This function returns an ID number that other functions can use to manipulate the shared memory segment. This ID is the shared memory Access ID, which, unlike the system ID, is passed as a parameter. Be careful not to confuse the two. If it fails, Shmop_open will return FALSE.
Shmop_open success, using IPCS-M, you can see the memory segment that you just created, note that the requested memory segment has strict permissions, such as the root user application, ordinary users do not have access to
2. Writing data to a memory segment
Use the Shmop_write function to write data to a shared memory block. The use of this function is simple, and it accepts only 3 parameters, as shown below.
<?php //这里shmid可以延用上一段代码返回的shmid$shmid = shmop_open(ftok(__FILE__,‘h‘), ‘c‘, 0644, 1024); shmop_write($shmid, "Hello World!", 0);?>
This function is similar to the Fwrite function, where there are three parameters. * First parameter (SHMID):IsSHMOPOPENReturnBackOfID,ItKnowledgeDon'tYouExerciseForOfSharedEnjoyWithinSaveBlock No. II parameter number ( Shmid): Is the ID returned by Shmopopen, which identifies the block of shared memory you are manipulating.? The second parameter, data: is what you want to store. * Third parameter ($offset): Is the location where you want to start writing. By default, we always use zero to indicate where to start writing.
Returns the result: This function returns FALSE on failure and returns the number of bytes written when successful.
3. Reading data from a memory segment
Reading data from a shared memory segment is straightforward. You only need an open memory segment and the Shmop_read function, which accepts three parameters as follows:
<?php $shmid = shmop_open(ftok(\__FILE_\_,‘h‘), ‘c‘, 0644, 1024);shmop_write($shmid, "Hello World\!", 0); var_dump(shmop_read($shmid, 0, 11)); ?>
- First parameter ($SHMID): Is the ID returned by Shmop_open, which identifies the shared memory block of your operation.
- Second parameter ($start): is the location that you want to read from the memory segment, which can always be 0, representing the beginning of the data
- A third parameter (COUNT):IsYouHLookReadTakeOfWordSectionNumber。OneLikeCiaConditionUnder I hm opsize ( count): Is the number of bytes you want to read. In general we use Shmopsize (Shmid) in order to read it completely.
4. Deleting memory segments
Shmop_delete the function receives only one parameter, as follows:
<?php $shmid = shmop_open(ftok(\__FILE_\_,‘h‘), ‘c‘, 0644, 1024);shmop_delete($shmid); ?>
In fact, this function does not actually delete the memory segment. It marks the memory segment as deleted because the shared memory segment cannot be deleted while another process is using it. The Shmop_delete function marks the memory segment as deleted, preventing any other process from opening it. To delete it, we need to close the memory segment.
5. Close the memory segment
Opening a shared memory segment is "attached" to it. After attaching the memory segment, we can read and write in it, but after the operation is complete, we must remove it from it.
<?php $shmid = shmop_open(ftok(\__FILE_\_,‘h‘), ‘c‘, 0644, 1024);shmop_write($shmid, "Hello World\!", 0); shmop_delete($shmid); shmop_close($shmid); ?>
Atomic operation of shared memory-signal control
The write operation for shared memory is not atomic in itself, so when we have a lot of concurrent read and write, how to guarantee atomicity, here to introduce the semaphore to control.
PHP also provides built-in extension sysvsem, in fact, when we look at the Sysvsem provided by a series of SEM* method, we will think, this and the above mentioned Shmop* What is the difference between, we look at the official room document This one explanation: PHP already Had a shared memory extension (SYSVSHM) written by Christian Cartus [email protected], unfortunately this extension was de Signed with PHP @ Mind and offers-level features which is extremely bothersome for basic SHM we had in mind.
In other words: The SYSVSHM extension provides a method to serialize the user's data before storing it, causing the stored data to not be shared with other languages, a method that PHP only has.
Example after the introduction of signal control:
<?php $key = ftok(_FILE_, ‘h‘) $mode = "c";$permissions = 0755;$size = 1024; // 内存段的大小,单位是字节$semid = sem_get($key); # 请求信号控制权if (sem_acquire($semid)) { $shmid = shmop_open($key, ‘c‘, 0644, 1024); # 读取并写入数据 shmop_write($shmid, ‘13800138000‘, 0); # 关闭内存块 shmop_close($shmid); # 释放信号 sem_release($semid);}
The operation of shared memory is very fast, and it is very difficult to locally try to emulate the write conflict, but it is actually very difficult for the local to emulate the implementation of the write conflict (taking into account the speed of the computer's execution). In a local test, when you use the For loop operation, if you close the resource without using Shmop_close, you will get an error warning that the shared memory cannot be opened. This should be caused by the fact that the shared memory was not released during the last operation.
PHP Shared Memory