Implementing interprocess Communication in PHP

Source: Internet
Author: User
Tags format file system implement mutex php script query unique id web services
Implementing interprocess communication in Process PHP

Chu Wenyu

This article discusses how to use the interprocess communication mechanism--IPC (inter-process-communication) in a PHP4 environment. The software environment discussed in this article is linux+php4.0.4 or later. First, let's say you've installed PHP4 and UNIX, and in order for PHP4 to be able to use shared memory and semaphores, you must activate both the SHMOP and Sysvsem extension modules when compiling the PHP4 program.
Implementation: Add the following options when setting up PHP (Configure).
--enable-shmop--enable-sysvsem
This allows your PHP system to handle the relevant IPC functions.
What is IPC?
IPC (inter-process communication) is a standard UNIX communication mechanism that provides a way to communicate with each other in different processes on the same host. There are 3 basic IPC processing mechanisms: Shared memory, semaphores, and message queues, respectively. In this article, we mainly discuss the use of shared memory and semaphores. About the message queue, the author in the near future will also be specifically introduced.
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 a 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 to implement real-time queries on the number of simultaneous PHP runs, and so on.
Shared memory allows two or more processes to share a given storage area. Because the data does not need to be replicated between the client and the server, this is the fastest IPC. The only trick to using shared memory is the simultaneous access of multiple processes to a given storage area.
How do I build 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 the shared memory segment. Different processes can share the same segment as long as the same key ID is selected. It is customary for us to use a hash value of a string (something like a filename) 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 you have already built, use the ' a ',--for access. The $perm parameter defines the access permissions, 8, and the Unix file system Help for permission definitions. $size defines the size of the shared memory. Although a bit like fopen (file processing) You don't want to be treated like a file. The following description you will see a little bit.
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 all the IPC resource states in the system. However, some system requirements require superuser to perform. The following figure shows the results of a IPCS operation.


The system shows 4 shared memory segments in the image above, noting that the 4th key value is 0X00000FF3 is created by the PHP program we just ran. Refer to the UNIX user manual for the use of IPCS.
How do I free 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 management directives:
IPCRM ID, ID is the ID you see with IPCS. It's not the same as the $id in your program. Be careful, however, that if you use IPCRM to delete shared memory segments, it is possible that other processes that do not know the situation have some unpredictable errors (often bad results) when referencing this defunct shared memory device.
How do I use (read and write) shared memory?
Write data to shared memory using the functions shown below
int shmop_write (int shmid, string data, int offset)
Where Shmid is the handle returned with the Shmop_open. The $Data variable holds the data to be stored. $offset describes where to write the first byte from the start of shared memory (starting with 0).
The read operation is:
String Shmop_read (int shmid, int start, int count)
Also, indicate the $SHMID, begin the offset (starting at 0), and the total number of reads. Returns the result string. This way, you can think of a shared memory segment as a byte array. Read a few and write a few, do what you want to do, very convenient.
Considerations for multiple process issues
Now, in a separate  rose 龃 Zhai eel with neon  荩  vermiculite  prostitution 诖  support Pro 苁 swear Onion armed mu 笾 phlegm which  谌荩 the ? The data written by the process turns randomly into a mixed four-image. This is clearly unacceptable. In order to solve this problem, we must introduce mutual exclusion mechanism. The mutual exclusion mechanism is specifically described in the textbooks of many operating systems, and there is little repetition here. The easiest 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 queues). It is a register that controls the storage of shared data by multiple processes. In the same way, you can use IPCS and IPCRM to implement a query of the state of the semaphore and to implement a delete operation. In PHP you can use the following function to create a new semaphore and return a handle to the semaphore. If the key points to a semaphore that already exists, the Sem_get directly returns the handle that is manipulating the semaphore.
int sem_get (int key [, int max_acquire] [, int perm]])
$max _acquire indicates that a maximum of several processes can be entered at the same time without waiting for the signal to be released (that is, the number of processes that handle a resource at the same time, typically the value is one). The $perm indicates access rights.
Once you successfully have a semaphore, you can do only 2 kinds of it: request, release. When you perform a release operation, the system will reduce the signal value by one. If less than 0, it is also set to 0. And when you perform a request operation, the system will add the signal value one, if the value is greater than the set maximum then the system will suspend your process until the other process is released to less than the maximum value. In general, the maximum is set to 1, so that when a process obtains a request, the other subsequent process can only wait for it to exit the mutex and then release the semaphore before it can enter the mutex and be set as exclusive. Such a semaphore is often referred to as a dual-state signal volume. 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 for the request and release operation is as follows:
int sem_acquire (int sem_identifier) request
int sem_release (int sem_identifier) free
Where Sem_identifier is the return value (handle) of the call Sem_get.
An example of a simple mutex protocol
Here 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 critical section/*
Here, the shared memory is processed
Sem_release ($semid); //Release
As you can see, the implementation of the mutex is simple: The request enters the critical section, operates on the critical area resources (such as modifying shared memory), exits the critical section and releases the signal. This ensures that there are no simultaneous 2 processes in the same time slice that can operate on the same segment of shared memory. Because the semaphore mechanism ensures that a time slice can only be entered by one process, the other processes must wait for the current process to complete before they can enter.
Critical areas are generally those that do not allow multiple concurrent processes to be processed concurrently by code snippets.
It is important to note that in PHP, the same process must be freed from the amount of semaphore it occupies. Allows processes to release signals that other processes occupy in the general system. In writing critical section Code must be careful to design the allocation of resources, to avoid a and so b,b, such as a deadlock situation occurred.
Used for transporting 
The application of IPC is very extensive. For example, save an interpreted complex profile, or a specific set of users, between different processes to avoid duplication of processing. I've also used shared memory technology to put a large file of PHP scripts into shared memory, which significantly improves the speed of Web services and eliminates some bottlenecks. About its use there are chat rooms, multicast, and so on. The power of IPC depends on the size of your imagination. If this article has a little inspiration for you, I would be honored. Willing to talk to you about 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.