_php Tutorial on implementing interprocess Communication in PHP

Source: Internet
Author: User
Implementing interprocess Communication in PHP

Chu Wenyu

This article will discuss how to use the interprocess 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, let's assume that you've installed PHP4 and UNIX, and in order for the PHP4 to use shared memory and semaphores, you must activate both the SHMOP and Sysvsem extensions when compiling the PHP4 program.
Implementation method: Add the following options when PHP is set (configure).
This allows your PHP system to handle the relevant IPC functions.
What is IPC?
The IPC (inter-process communication) is a UNIX standard communication mechanism that provides a way to communicate with each other between different processes in the same host. There are 3 basic IPC processing mechanisms: They are shared memory, semaphores, and message queues, respectively. In this article we mainly discuss the use of shared memory and semaphore. About Message Queuing, the author will be specially introduced in the near future.
Using shared memory segments in PHP
Using shared memory between different processing processes is a good way to achieve 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 data being written. 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 implement a real-time query on the number of concurrent PHP runs, and so on.
Shared memory allows two or more processes to share a given storage area. This is the fastest IPC because the data does not need to be replicated between the client and the server. The only trick to using shared memory is that multiple processes synchronize access to a given storage area.
How do I create a shared memory segment? The following code can help you build shared memory.
$shm _id = Shmop_open ($key, $mode, $perm, $size);
Note that each shared memory segment has a unique ID, and in PHP, Shmop_open returns the ID of the established shared memory segment, where we use $shm_id to record it. And $key is a key value that we logically represent shared memory segments. Different processes can share the same segment of a bucket simply by selecting the same key ID. We used the hash value of a string (something like the file name) as the key ID. $mode indicates how shared memory segments are used. This is because it is new, so the value is ' C ' – take the meaning of create. If you are accessing shared memory that has already been established, then use the ' a ',--access. $perm parameters define access permissions, 8 binary, see UNIX File system Help for permission definitions. $size defines the size of the shared memory. Although a bit like fopen (file processing) you should not treat it as if it were a file. You will see a little bit of the following 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 with a size of 100 bytes.
If you need to access an existing shared memory segment, you must set the 3rd, 4 parameters to 0 in the call Shmop_open.
Query for IPC working status
Under UNIX, you can use a command-line program to IPCS the status of all IPC resources in the system. However, some systems require super users to perform. Is the result of a IPCS operation.

The system shows 4 shared memory segments, noting that the 4th key value for 0X00000FF3 is created by the PHP program we just ran. Refer to the UNIX user manual for IPCS usage.
How to free up shared memory?
The way to free shared memory is to invoke the PHP Directive: Shmop_delete ($ID)
Shmop_delete ($id);
$id is the return value of the shmop_op that you call Shmop_open. Another option is to use UNIX's management directives:
IPCRM ID, ID is the ID you see with IPCS. Not the same as the $id in your program. But be careful if you use IPCRM to directly delete shared memory segments then it is possible to cause other processes that do not know this to have some unpredictable errors (often bad results) when referencing the shared memory that is no longer present.
How to use (Read and write) shared memory?
Write data to shared memory using the function shown below
int shmop_write (int shmid, string data, int offset)
Where Shmid is the handle returned with Shmop_open. The $Data variable holds the data to be stored. $offset describes where to write the first byte from the beginning of shared memory (starting at 0).
The read operation is:
String Shmop_read (int shmid, int start, int count)
Also, indicate $shmid, start offset (starting at 0), total read quantity. Returns the result string. This way, you can think of the shared memory segment as a byte array. Read a few and write a few, what you want to do, very convenient.
Considerations for multi-process issues
Now, in a single Mei Jie Huan irregular zhai eel with neon invironment vermiculite Axmanovs prostitute allowance Tiger Pro swear 笾 onion weapon mu phlegm which 谌荩 inspectors Liao timid? The data written by the process is rotated randomly to appear a mixed four-way. This is obviously unacceptable. In order to solve this problem, we must introduce mutual exclusion mechanism. Mutual exclusion mechanisms are specifically described in the textbooks of many operating systems, where there is little repetition. The simplest way to implement a mutex is to use a semaphore. Semaphores are another way of interprocess communication (IPC), which differs from other IPC mechanisms (pipelines, FIFO, Message Queuing). It is a register for controlling the storage of shared data by multiple processes. Also, you can use IPCS and IPCRM to implement a query and delete operations on the semaphore's status. In PHP you can create a new semaphore with the following function and return a handle to the semaphore. If the key is pointing to a semaphore that already exists, Sem_get directly returns a handle to the semaphore operation.
int sem_get (int key [, int max_acquire] [, int perm]])
$max _acquire indicates that at the same time a maximum of several processes can be used to enter the signal without waiting for the signal to be released (that is, the maximum number of processes that handle a resource at the same time, which is generally a value of one). The $perm indicates access rights.
Once you have a successful semaphore, there are only 2 things you can do about it: request, release. When you perform the release operation, the system will reduce the signal value by one. If it is less than 0 then it is also set to 0. And when you perform the request operation, the system will add one to the signal value, if the value is greater than the set maximum then the system will suspend your processing process until other processes are released to less than the maximum value. In general, the maximum value is set to 1 so that when a process obtains a request, the other process can only wait until it exits the mutex to release the semaphore before it can enter the mutex and is also set to exclusive. Such a semaphore is often called a two-state semaphore. Of course, if the initial value is any positive number, it indicates how many shared resource units are available for sharing the app.
The PHP format for application and release operations is as follows:
int sem_acquire (int sem_identifier) request
int sem_release (int sem_identifier) release
Where Sem_identifier is the return value (handle) of the call to Sem_get.
An example of a simple mutex protocol
The following is a very simple mutex operation.
$semid =sem_get (0xee3,1,0666);
$shm _id = Shmop_open (0XFF3, "C", 0644, 100);
Sem_acquire ($semid); Application
/* Enter the critical section */
Here, the shared memory is processed
Sem_release ($semid); Release
As you can see, the implementation of the mutex is simple: apply to the critical section, operate on critical section resources (such as modifying shared memory) and exit the critical section and release the signal. In this way, it is guaranteed that 2 simultaneous processes in the same time slice will not be able to operate on the same piece of shared memory. 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.
A critical section generally refers to code snippets that do not allow concurrent processing of multiple processes at the same time.
It is important to note that in PHP, the amount of semaphores that it consumes must be released by the same process. In a generic system, a process is allowed to release signals that are consumed by other processes. In writing the critical section code must be careful to design the allocation of resources to avoid a b,b such as a deadlock situation occurs.
The use of IPC is very extensive. For example, a complex configuration file that has been interpreted, or a specific set of users, is saved between different processes to avoid duplication of processing. I've also used the technology of shared memory to put a large number of PHP scripts that must be referenced into shared memory, which significantly improves the speed of Web services and eliminates some of the bottlenecks. There are also chat rooms, multi-channel broadcasts and so on for its use. The power of IPC depends on the size of your imagination. If this article is a little bit of inspiration to you, then I am greatly honored. Would like to discuss this fascinating computer technology with you. Email:qwyaxm@163.net

http://www.bkjia.com/PHPjc/314816.html www.bkjia.com true http://www.bkjia.com/PHPjc/314816.html techarticle implementing interprocess Communication in PHP Chu Wenyu This article will discuss how to use the interprocess communication mechanism--IPC (inter-process-communication) in the PHP4 environment. The software environment discussed in this paper is Linux+p ...

  • Related Article

    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.