Home  >  Article  >  Backend Development  >  Implementing inter-process communication in PHP_PHP tutorial

Implementing inter-process communication in PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 16:08:24849browse

Implementing inter-process communication in PHP

Qiu Wenyu

This article will discuss how to use the inter-process communication mechanism - IPC (Inter-Process-Communication) in the PHP4 environment. The software environment discussed in this article is linux+php4.0.4 or higher. First, we assume that you have installed PHP4 and UNIX. In order for php4 to use shared memory and semaphores, the two extension modules shmop and sysvsem must be activated when compiling the php4 program.
Implementation method: Add the following options when setting up PHP (configure).
--enable-shmop --enable-sysvsem
This will enable your PHP system to handle related IPC functions.
What is IPC?
IPC (Inter-process communication) is a Unix standard communication mechanism that provides a method for different processes on the same host to communicate with each other. There are three basic IPC processing mechanisms: shared memory, semaphores and message queues. In this article we mainly discuss the use of shared memory and semaphores. Regarding the message queue, the author will introduce it specifically in the near future.
Using shared memory segments in PHP
Using shared memory between different processing processes is a good way to achieve mutual communication between different processes. If you write a piece of information to shared memory in one process, then all other processes can also see the written data. Very convenient. With the help of shared memory in PHP, you can achieve different results when different processes run the same PHP script. Or implement real-time query on the number of PHP running at the same time, etc.
Shared memory allows two or more processes to share a given storage area. Because data does not need to be copied between the client and server, this is the fastest type of IPC. The only trick to using shared memory is the simultaneous access of multiple processes to a given memory area.
How to create a shared memory segment? The following code can help you create shared memory.
$shm_id = shmop_open($key, $mode, $perm, $size);
Note that each shared memory segment has a unique ID. In PHP, shmop_open will store the created shared memory The ID of the segment is returned, here we record it with $shm_id. And $key is a Key value that we logically represent the shared memory segment. Different processes can share the same storage segment as long as they choose the same Key id. It is customary for us to use the hash value of a string (something like a file name) as the key id. $mode specifies how the shared memory segment is used. Since this is a new creation, the value is 'c' - which means create. If you are accessing shared memory that has been created, please use 'a', which means access. The $perm parameter defines the access permissions, in octal format. Please see the UNIX file system help for permission definitions. $size defines the size of shared memory. Although it is a bit like fopen (file processing), you should not think of it as the same as file processing. You will see a little bit of this later in the description.
For example:
$shm_id = shmop_open(0xff3, "c", 0644, 100);
Here we open a shared memory segment key value 0xff3 –rw-r—r— format, size 100 byte.
If you need to access an existing shared memory segment, you must set the 3rd and 4th parameters to 0 when calling shmop_open.
IPC working status query
Under Unix, you can use a command line program ipcs to query the status of all IPC resources in the system. However, some system requirements require superuser to perform. The picture below is a section of ipcs running results.


In the picture above, the system shows 4 shared memory segments. Note that the fourth key value is 0x00000ff3, which was created by the PHP program we just ran. For the usage of ipcs, please refer to the UNIX User Manual.
How to release shared memory
The way to release shared memory is to call the PHP command: shmop_delete($id)
shmop_delete($id);
$id is the return value of shmop_op saved by calling shmop_open . Another way is to use the UNIX management command:
ipcrm id. The id is the ID you see using ipcs. It is different from the $id in your program. But be careful, if you use ipcrm to directly delete the shared memory segment, it may cause other processes that are unaware of this situation to cause some unpredictable errors (often with unfavorable results) when referencing this shared memory that no longer exists.
How to use (read and write) shared memory
Use the function shown below to write data to shared memory
int shmop_write (int shmid, string data, int offset)
where shmid is returned by shmop_open handle. The $Data variable stores the data to be stored. $offset describes the position of writing the first byte from the beginning of shared memory (starting with 0).
The read operation is:
string shmop_read (int shmid, int start, int count)
Similarly, specify $shmid, starting offset (starting with 0), and total number of reads. Return the result string. In this way, you can treat the shared memory segment as a byte array. You can read a few and write a few, and you can do whatever you want. It's very convenient.
Consideration of multi-process issues
Now, in a separate process, in a separate The data written by two processes takes turns to appear randomly in a mixed sequence. This is obviously unacceptable. In order to solve this problem, we must introduce a mutual exclusion mechanism.The mutual exclusion mechanism is specifically described in many operating system textbooks, so I won’t repeat it here. The simplest way to implement a mutual exclusion mechanism is to use semaphores. Semaphore is another method of inter-process communication (IPC), which is different from other IPC mechanisms (pipeline, FIFO, message queue). It is a counter used to control the storage of shared data by multiple processes. Similarly, you can use ipcs and ipcrm to query the status of semaphores and delete them. In PHP you can use the following functions to create a new semaphore and return a handle to the semaphore. If the semaphore pointed to by the key already exists, sem_get directly returns the handle to operate the semaphore.
int sem_get (int key [, int max_acquire ][, int perm]])
$max_acquire indicates that up to several processes can be used to enter the signal at the same time without waiting for the signal to be released (that is, the maximum number of processes that can be processed simultaneously is The number of processes for a resource, generally the value is one). $perm specifies access permissions.
Once you successfully own a semaphore, there are only two things you can do with it: request and release. When you perform a release operation, the system will decrease the signal value by one. If it is less than 0, set it to 0. When you perform the requested operation, the system will increase the signal value by one. If the value is greater than the set maximum value, the system will suspend your processing process until other processes are released to a value less than the maximum value. Under normal circumstances, the maximum value is set to 1, so that when a process obtains a request, other subsequent processes can only wait for it to exit the mutex area and then release the semaphore before entering the mutex area and setting it to exclusive mode at the same time. Such semaphores are often called binary semaphores. Of course, if the initial value is any positive number, it indicates how many shared resource units are available for shared applications.
The PHP format of application and release operations is as follows:
int sem_acquire (int sem_identifier) ​​application
int sem_release (int sem_identifier) ​​release
where sem_identifier is the return value (handle) of calling sem_get.
A simple example of mutual exclusion protocol
The following is a very simple mutual exclusion operation procedure.
$semid=sem_get(0xee3,1,0666);
$shm_id = shmop_open(0xff3, "c", 0644, 100);
sem_acquire($semid); // Apply
/* Enter critical section*/
Here, the shared memory is processed
sem_release($semid); //Release
As you can see, The implementation of mutual exclusion is very simple: apply to enter the critical section, operate the critical section resources (such as modifying shared memory), exit the critical section and release the signal. This ensures that it is impossible for two processes to operate on the same shared memory in the same time slice. Because the semaphore mechanism guarantees that a time slice can only be entered by one process, other processes must wait for the currently processed process to complete before they can enter.
Critical sections generally refer to code segments that do not allow concurrent processing by multiple processes at the same time.
It should be noted that in PHP, the semaphore it occupies must be released by the same process. In general systems, processes are allowed to release signals occupied by other processes. When writing critical section code, you must carefully design the allocation of resources to avoid deadlock situations where A waits for B, and B waits for A.
Usage
IPC is widely used. For example, saving an explained complex configuration file, or specific user settings, etc. between different processes to avoid duplication of processing. I also used shared memory technology to put a large file that a large number of PHP scripts must reference into shared memory, which significantly improved the speed of Web services and eliminated some bottlenecks. Regarding its use, there are chat rooms, multicasts, etc. The power of IPC depends on your imagination. If this article has inspired you even a little bit, I would be honored. I'd love to discuss this fascinating computer technology with you. Email: qwyaxm@163.net

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/314816.htmlTechArticle Implementing inter-process communication in PHP Qiu Wenyu This article will discuss how to use the inter-process communication mechanism - IPC ( Inter-Process-Communication). The software environment discussed in this article is linux+p...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn