Detailed explanation of PHP inter-process communication

小云云
Release: 2023-03-21 12:32:01
Original
5146 people have browsed it

A process is a running activity of a program with independent functions on a certain data collection. In other words, it is the basic unit of a program when the system schedules multiple CPUs. Process is not an unfamiliar concept to most languages, and as "the best language in the world, PHP" is certainly an exception.

Environment

The process in php is completed in the form of expansion. Through these extensions, we can easily complete a series of actions in the process.

  • pcntl extension: The main process extension, the completion process is created in the waiting operation.

  • posix extension: Complete common APIs for POSIX compatible machines, such as getting process id, killing processes, etc.

  • sysvmsg extension: message queue that implements system v inter-process communication.

  • sysvsem extension: implements the system v semaphore.

  • sysvshm extension: implements shared memory in system v mode.

  • sockets extension: implements socket communication.

These extensions can only be used in linux/mac, and are not supported under windows. Finally, it is recommended that the PHP version is 5.5+.

Simple example

A simple PHP multi-process example. In this example, there is a child process and a parent process. The child process outputs 5 times and exits the program.

$parentPid = posix_getpid();
echo "parent progress pid:{$parentPid}\n";
$childList = array();
$pid = pcntl_fork();
if ( $pid == -1) {
    // 创建失败
    exit("fork progress error!\n");
} else if ($pid == 0) {
    // 子进程执行程序
    $pid = posix_getpid();
    $repeatNum = 5;
    for ( $i = 1; $i <= $repeatNum; $i++) {
        echo "({$pid})child progress is running! {$i} \n";
        $rand = rand(1,3);
        sleep($rand);
    }
    exit("({$pid})child progress end!\n");
} else {
    // 父进程执行程序
    $childList[$pid] = 1;
}
// 等待子进程结束
pcntl_wait($status);
echo "({$parentPid})main progress end!";
Copy after login

Perfect, finally created a child process and a parent process. Is it over? No, each process is independent of each other, there is no intersection, and the scope of use is severely limited. What to do? Let’s use interprogress communication.

4. Inter-process Communication (IPC)

Usually the process communication methods in Linux include: message queue, semaphore, shared memory, signal, pipe, and socket.

1. Message Queue

The message queue is a queue stored in memory. The following code will create 3 producer sub-processes and 2 consumer sub-processes. These 5 processes will communicate through the message queue.

$parentPid = posix_getpid();
echo "parent progress pid:{$parentPid}\n";$childList = array();
// 创建消息队列,以及定义消息类型(类似于数据库中的库)
$id = ftok(__FILE__,&#39;m&#39;);
$msgQueue = msg_get_queue($id);
const MSG_TYPE = 1;
// 生产者
function producer(){
    global $msgQueue;
    $pid = posix_getpid();
    $repeatNum = 5;
    for ( $i = 1; $i <= $repeatNum; $i++) {
        $str = "({$pid})progress create! {$i}";
        msg_send($msgQueue,MSG_TYPE,$str);
        $rand = rand(1,3);
        sleep($rand);
    }
}
// 消费者
function consumer(){
    global $msgQueue;
    $pid = posix_getpid();
    $repeatNum = 6;
    for ( $i = 1; $i <= $repeatNum; $i++) {
        $rel = msg_receive($msgQueue,MSG_TYPE,$msgType,1024,$message);
        echo "{$message} | consumer({$pid}) destroy \n";
        $rand = rand(1,3);
        sleep($rand);
    }
}
function createProgress($callback){
    $pid = pcntl_fork();
    if ( $pid == -1) {
        // 创建失败
        exit("fork progress error!\n");
    } else if ($pid == 0) {
        // 子进程执行程序
        $pid = posix_getpid();
        $callback();
        exit("({$pid})child progress end!\n");
    }else{
        // 父进程执行程序
        return $pid;
    }
}
// 3个写进程
for ($i = 0; $i < 3; $i ++ ) {
    $pid = createProgress(&#39;producer&#39;);
    $childList[$pid] = 1;
    echo "create producer child progress: {$pid} \n";
}
// 2个写进程
for ($i = 0; $i < 2; $i ++ ) {
    $pid = createProgress(&#39;consumer&#39;);
    $childList[$pid] = 1;
    echo "create consumer child progress: {$pid} \n";
}
// 等待所有子进程结束
while(!empty($childList)){
    $childPid = pcntl_wait($status);
    if ($childPid > 0){
        unset($childList[$childPid]);
    }
}
echo "({$parentPid})main progress end!\n";
Copy after login

Since the message queue can only access data by one process, no additional locks or semaphores are required.

2. Semaphore and shared memory

Semaphore: It is an atomic operation provided by the system, a semaphore, and only your process can operate it at the same time. When a process obtains a semaphore, it must be released by the process.

Shared memory: It is a common memory area opened by the system in the memory. Any process can access it. At the same time, multiple processes can access this area. In order to ensure the consistency of data, it is necessary to Lock or semaphore this memory area.

Below, multiple processes are created to modify the same value in memory.

$parentPid = posix_getpid();
echo "parent progress pid:{$parentPid}\n";
$childList = array();
 
// 创建共享内存,创建信号量,定义共享key
$shm_id = ftok(__FILE__,&#39;m&#39;);
$sem_id = ftok(__FILE__,&#39;s&#39;);
$shareMemory = shm_attach($shm_id);
$signal = sem_get($sem_id);
const SHARE_KEY = 1;
// 生产者
function producer(){
    global $shareMemory;
    global $signal;
    $pid = posix_getpid();
    $repeatNum = 5;
    for ( $i = 1; $i <= $repeatNum; $i++) {
        // 获得信号量
        sem_acquire($signal);
 
        if (shm_has_var($shareMemory,SHARE_KEY)){
            // 有值,加一
            $count = shm_get_var($shareMemory,SHARE_KEY);
            $count ++;
            shm_put_var($shareMemory,SHARE_KEY,$count);
            echo "({$pid}) count: {$count}\n";
        }else{
            // 无值,初始化
            shm_put_var($shareMemory,SHARE_KEY,0);
            echo "({$pid}) count: 0\n";
        }
        // 用完释放
        sem_release($signal);
 
        $rand = rand(1,3);
        sleep($rand);
    }
}
function createProgress($callback){
    $pid = pcntl_fork();
    if ( $pid == -1) {
        // 创建失败
        exit("fork progress error!\n");
    } else if ($pid == 0) {
        // 子进程执行程序
        $pid = posix_getpid();
        $callback();
        exit("({$pid})child progress end!\n");
    }else{
        // 父进程执行程序
        return $pid;
    }
}
// 3个写进程
for ($i = 0; $i < 3; $i ++ ) {
    $pid = createProgress(&#39;producer&#39;);
    $childList[$pid] = 1;
    echo "create producer child progress: {$pid} \n";
}
// 等待所有子进程结束
while(!empty($childList)){
    $childPid = pcntl_wait($status);
    if ($childPid > 0){
        unset($childList[$childPid]);
    }
}
// 释放共享内存与信号量
shm_remove($shareMemory);
sem_remove($signal);
echo "({$parentPid})main progress end!\n";
Copy after login

3. Signal

The signal is a system call. Usually the kill command we use is to send a certain signal to a certain process. You can check the specific signals by running kill -l in liunx/mac. In the following example, the parent process waits for 5 seconds and sends the sigint signal to the child process. The child process captures the signal and processes it with the signal processing function.

$parentPid = posix_getpid();
echo "parent progress pid:{$parentPid}\n";
 
// 定义一个信号处理函数
function sighandler($signo) {
    $pid = posix_getpid();
    echo "{$pid} progress,oh no ,I&#39;m killed!\n";
    exit(1);
}
 
$pid = pcntl_fork();
if ( $pid == -1) {
    // 创建失败
    exit("fork progress error!\n");
} else if ($pid == 0) {
    // 子进程执行程序
    // 注册信号处理函数
    declare(ticks=10);
    pcntl_signal(SIGINT, "sighandler");
    $pid = posix_getpid();
    while(true){
        echo "{$pid} child progress is running!\n";
        sleep(1);
    }
    exit("({$pid})child progress end!\n");
}else{
    // 父进程执行程序
    $childList[$pid] = 1;
    // 5秒后,父进程向子进程发送sigint信号.
    sleep(5);
    posix_kill($pid,SIGINT);
    sleep(5);
}
echo "({$parentPid})main progress end!\n";
Copy after login

4. Pipes (named pipes)

Pipes are a commonly used means of multi-process communication. Pipes are divided into unnamed pipes and named pipes. Unnamed pipes can only be used for processes that have related relationships. Communication between processes, and named pipes can be used by any process on the same host. Only famous channels are introduced here. In the following example, the child process writes data and the parent process reads data.

// 定义管道路径,与创建管道
$pipe_path = &#39;/data/test.pipe&#39;;
if(!file_exists($pipe_path)){
    if(!posix_mkfifo($pipe_path,0664)){
        exit("create pipe error!");
    }
}
$pid = pcntl_fork();
if($pid == 0){
    // 子进程,向管道写数据
    $file = fopen($pipe_path,&#39;w&#39;);
    while (true){
        fwrite($file,&#39;hello world&#39;);
        $rand = rand(1,3);
        sleep($rand);
    }
    exit(&#39;child end!&#39;);
}else{
    // 父进程,从管道读数据
    $file = fopen($pipe_path,&#39;r&#39;);
    while (true){
        $rel = fread($file,20);
        echo "{$rel}\n";
        $rand = rand(1,2);
        sleep($rand);
    }
}
Copy after login

Related recommendations:

How to implement PHP process lock

Summary of points to note about PHP process communication

Semaphore and shared memory communication based on PHP process communication

The above is the detailed content of Detailed explanation of PHP inter-process communication. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!