search
HomeBackend DevelopmentPHP TutorialDetailed introduction to the code used by php shared memory

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 allows 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 return the ID of the created shared memory segment. Here 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 storage segment as long as they select 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 with the key value 0xff3 –rw-r—r— format and a size of 100 bytes.

If you need to access an existing shared memory segment, you must set the third and fourth 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 displays 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 what you call The return value of shmop_op stored in 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 uses shmop_open The handle returned. 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)

  同样,指明$shmid,开始偏移量(以0开始)、总读取数量。返回结果串。这样,你就可以把共享内存段当作是一个字节数组。读几个再写几个,想干嘛就干嘛,十分方便。

  多进程问题的考虑

  现在,在单独的一个PHP进程中读写、创建、删除共享内存方面上你应该没有问题了。但是,显然实际运行中不可能只是一个PHP进程在运行中。如果在多个进程的情况下你还是沿用单个进程的处理方法,你一定会碰到问题 ---- 著名的并行和互斥问题。比如说有2个进程同时需要对同一段内存进行读写。当两个进程同时执行写入操作时,你将得到一个错误的数据,因为该段内存将之可能是最后执行的进程的内容,甚至是由2个进程写入的数据轮流随机出现的一段混合的四不象。这显然是不能接受的。为了解决这个问题,我们必须引入互斥机制。互斥机制在很多操作系统的教材上都有专门讲述,这里不多重复。实现互斥机制的最简单办法就是使用信号灯。信号量是另外一种进程间通讯(IPC)的方式,它同其他IPC机构(管道、FIFO、消息队列)不同。它是一个记数器,用于控制多进程对共享数据的存储。同样的是你可以用ipcs和ipcrm实现对信号灯使用状态的查询和对其实现删除操作。在PHP中你可以用下列函数创建一个新的信号量并返回操作该信号量的句柄。如果该key指向的信号量已经存在,sem_get直接返回操作该信号量的句柄。

int sem_get (int key [, int max_acquire [, int perm]])

  $max_acquire 指明同时最多可以用几个进程进入该信号而不必等待该信号被释放(也就是最大同时处理某一资源的进程数目,一般该值均为一)。$perm指明了访问权限。

  一旦你成功的拥有了一个信号量,你对它所能做的只有2种:请求、释放。当你执行释放操作时, 系统将把该信号值减一。如果小于0那就还设为0。而当你执行请求操作时,系统将把该信号值加一,如果该值大于设定的最大值那么系统将挂起你的处理进程直到其他进程释放到小于最大值为止。一般情况下最大值设为1,这样一来当一个进程获得请求时其他后面的进程只能等待它退出互斥区后释放信号量才能进入该互斥区并同时设为独占方式。这样的信号量常称为双态信号量。当然,如果初值是任意一个正数就表明有多少个共享资源单位可供共享应用。

  申请、释放操作的PHP格式如下:

int sem_acquire (int sem_identifier) 申请 
int sem_release (int sem_identifier) 释放 
其中sem_identifier是调用sem_get的返回值(句柄)。  
一个简单的互斥协议例子 
下面是一段很简单的互斥操作规程。 
$semid=sem_get(0xee3,1,0666); 
$shm_id = shmop_open(0xff3, "c", 0644, 100); 
sem_acquire($semid);      //申请 
/* 进入临界区*/ 
这里,对共享内存进行处理 
sem_release($semid);      //释放

  正如你所看到的,互斥的实现很简单:申请进入临界区,对临界区资源进行操作(比如修改共享内存)退出临界区并释放信号。这样一来就可以保证在同一个时间片中不可能有同时2个进程对同一段共享内存进行操作。因为信号量机制保证一个时间片只能由一个进程进入,其他进程必须等待当前处理的进程完成后方能进入。

  临界区一般是指那些不允许同时有多个进程并发处理的代码段。

  要注意的是:在PHP中必须由同一个进程释放它所占用的信号量。在一般系统中允许进程释放别的进程占用的信号。在编写临界区代码一定要小心设计资源的分配,避免A等B,B等A的死锁情况发生。

  运 用

  IPC的运用是十分广泛的。比如,在不同进程间保存一个解释过的复杂的配置文件、或具体设置的用户等,以避免重复处理。我也曾经用共享内存的技术把一大批PHP脚本必须引用的一个很大的文件放入共享内存,并由此显著提升了Web服务的速度、消除了部分瓶颈。关于它的使用还有聊天室,多路广播等等。IPC的威力取决于你的想象力的大小。如果本文对你有一点点启发,那我不胜荣幸。愿意很你讨论这令人入迷的电脑技术。

<?php
//print_r($res_area);
//$res_area = array("username" => "yanjing5462","password" => "132");
$new_area = serialize($res_area);
//申请共享内存空间
$shm_id = @shmop_open(0xff9, "a", 0, 0);
if(empty($shm_id))
{
echo "创建";
$shm_id = shmop_open(0xff9, "c", 0700, 1048576); //10MB
//$value = "我国已成为全球能源建设规模最大的市场";
//写入共享内存空间
echo $shm_id;
shmop_write($shm_id, $new_area, 0);
  }
else
{
echo &#39;不创建&#39;.time();
shmop_delete($shm_id);
shmop_close($shm_id);
}
$shmid = shmop_open(0xff9, "a", 0, 0);
  $my_string = shmop_read($shmid, 0, 1048576);
  print_r( unserialize($my_string) );
?>

 以上就是php共享内存使用的代码详细介绍的内容,更多相关内容请关注PHP中文网(www.php.cn)!



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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.