Implement inter-process communication in PHP

Source: Internet
Author: User
Qiu Wenyu 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 later. First, assume that you have installed PHP4 and UNIX. to enable php4 to use shared memory and semaphores, you must activate the shmop and sysvsem parameters when compiling the php4 program.

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 later. First, assume that you have installed PHP4 and UNIX. to enable php4 to use shared memory and semaphores, you must activate the shmop and sysvsem extension modules when compiling the php4 program.
Implementation Method: Add the following options when configuring configure in PHP.
-- Enable-shmop -- enable-sysvsem
This allows your PHP system to process related IPC functions.
What is IPC?
IPC (Inter-process communication) is a Unix standard communication mechanism, which provides a method for communication between different processes on the same host. There are three basic IPC processing mechanisms: Shared Memory, Semaphore, and message queue. This article mainly discusses the use of shared memory and semaphores. I will introduce the message queue in the near future.
Use 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 the shared memory in a process, all other processes can also see the written data. Very convenient. With the help of shared memory in PHP, you can implement different processes to return different results when running the same PHP script. Or real-time query of the number of concurrent PHP operations.
Shared memory allows two or more processes to share a given storage zone. Because data does not need to be copied between the client and the server, this is the fastest IPC. The only trick to using shared memory is the synchronous access of multiple processes to a given storage zone.
How to create a shared memory segment? The following code helps 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 returns the ID of the created shared memory segment. here we use $ shm_id to record it. $ Key is a Key value that logically represents the shared memory segment. Different processes can share the same bucket with the same Key id. Traditionally, we use the hash value of a string (something similar to a file name) as the key id. $ mode to indicate how to use the shared memory segment. Here, because it is a new one, the value is 'c'-the meaning of "create. If you are accessing the shared memory that has been created, use 'a', -- the meaning of access. The $ perm parameter defines the access permission in octal mode. for the permission definition, see the UNIX file system help. $ Size defines the size of the shared memory. Although it is a bit like fopen (file processing), you should not treat it like file processing. You will see a bit later.
For example:
$ Shm_id = shmop_open (0xff3, "c", 0644,100 );
Here we open a shared memory segment key value 0xff3-rw-r-format, the size is 100 bytes.
To access an existing shared memory segment, you must set the 3rd and 4 parameters to 0 in the call to shmop_open.
Query the IPC working status
In Unix, you can use the command line program ipcs to query the status of all IPC resources. However, some systems require super users to execute them. Is the running result of a piece of ipcs.


The system displays four shared memory segments. Note that the 4th key values 0x00000ff3 are created by the PHP program we just run. For instructions on ipcs usage, refer to the UNIX user manual.
How to release the shared memory?
To release the shared memory, call the PHP command: shmop_delete ($ id)
Shmop_delete ($ id );
$ Id is the return value of the shmop_op stored in the call shmop_open. Another way is to use UNIX management commands:
Ipcrm id. id is the ID you see in ipcs. it is different from $ id in your program. But be careful, if you use ipcrm to directly delete shared memory segments, other processes that do not know this situation may encounter some unpredictable errors when referencing this no longer-existing shared memory device (often bad results ).
How to use (read/write) shared memory?
Use the following function to write data to the shared memory:
Int shmop_write (int shmid, string data, int offset)
Here, shmid uses the handle returned by shmop_open. $ Data variable stores the Data to be stored. $ Offset describes the position of the first byte from the beginning of the shared memory (starting with 0 ).
The read operation is:
String shmop_read (int shmid, int start, int count)
Similarly, specify $ shmid, start offset (starting from 0), and total number of reads. Return result string. In this way, you can regard the shared memory segment as a byte array. It is very convenient to read a few and write a few more.
Multi-process considerations
Now, you should be able to read, write, create, and delete shared memory in a separate PHP process. However, it is clear that a PHP process is not running. If you still use the processing method of a single process in the case of multiple processes, you will certainly encounter problems-the famous parallel and mutex problems. For example, two processes need to read and write the same memory segment at the same time. When the two processes perform the write operation at the same time, you will get an error because the memory of this segment may be the content of the last executed process, even the data written by two processes takes turns to show a random mix of four. This is obviously unacceptable. To solve this problem, we must introduce the mutex mechanism. The mutex mechanism is described in many operating system textbooks. The simplest way to implement mutex is to use traffic signals. Semaphores are another way of inter-process communication (IPC), which is different from other IPC organizations (pipelines, FIFO, message queues. It is a stenographer used to control the storage of shared data by multiple processes. Similarly, you can use ipcs and ipcrm to query the traffic signal usage status and delete it. In PHP, you can use the following functions to create a new semaphore and return the handle to operate the semaphore. If the semaphore to which the key points 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 a maximum of several processes can enter the signal at the same time without waiting for the signal to be released (that is, the maximum number of processes that process a resource at the same time. Generally, this value is one ). $ Perm indicates the access permission.
Once you successfully have a semaphore, there are only two types of semaphore that you can do: request and release. When you perform the release operation, the system will reduce the signal value by one. If it is less than 0, it is also set to 0. When you execute the request, the system will increase the value of this signal. 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. Generally, the maximum value is set to 1, in this way, when a process receives a request, other processes can only wait for it to exit the mutex zone and release the semaphore to enter the mutex zone and set it to the exclusive mode at the same time. Such Semaphores are often called two-state semaphores. Of course, if the initial value is any positive number, it indicates how many shared resource units are available to the shared application.
The PHP format for application and release operations is as follows:
Int sem_acquire (int sem_identifier) application
Int sem_release (int sem_identifier) released
Specifically, sem_identifier is the return value (handle) of sem_get ).
An example of a simple mutex protocol
The following is a simple mutex operation procedure.
$ Semid = sem_get (0xee3, 1,0666 );
$ Shm_id = shmop_open (0xff3, "c", 0644,100 );
Sem_acquire ($ semid); // Apply
/* Enter the critical section */
Here, the shared memory is processed
Sem_release ($ semid); // release
As you can see, the implementation of mutex is very simple: apply to enter the critical section, perform operations on the resources in the critical section (such as modifying the shared memory) to exit the critical section and release the signal. In this way, it is impossible for two processes to operate on the same shared memory segment at the same time. Because the semaphore mechanism ensures that a time slice can only be entered by one process, other processes must wait until the current process is completed before entering.
A critical section is a code segment that does not allow concurrent processing by multiple processes at the same time.
Note: In PHP, the semaphore occupied by the same process must be released. In a general system, processes are allowed to release signals occupied by other processes. When writing code in the critical section, be sure to carefully design the allocation of resources to avoid deadlock between A, B, and.
Application
IPC is widely used. For example, you can save a complex configuration file or user with specific settings between different processes to avoid repeated processing. I also used the shared memory technology to put a large number of files that must be referenced by a large number of PHP scripts into the shared memory, which significantly improves the Web service speed and eliminates some bottlenecks. There are also chat rooms and multi-channel broadcasts for its use. The power of IPC depends on the size of your imagination. It is a great honor for me to give you some inspiration in this article. I 'd like you to discuss this fascinating computer technology. Email: qwyaxm@163.net

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.