Table of Contents
pcntl_signal" >pcntl_signal
posix_kill" > posix_kill
##pcntl_signal_dispatch##pcntl_signal_dispatch, calling the processor waiting for the signal" >##pcntl_signal_dispatch##pcntl_signal_dispatch, calling the processor waiting for the signal
We know what we know before You can monitor signals by combining declare(ticks=1) and pcntl_signal. That is, every low-level PHP statement will check whether there are unprocessed signals in the current process. This is actually very performance-consuming. " >3. The way to handle semaphores in PHPWe know what we know before You can monitor signals by combining declare(ticks=1) and pcntl_signal. That is, every low-level PHP statement will check whether there are unprocessed signals in the current process. This is actually very performance-consuming.
Home Backend Development PHP Tutorial A thorough understanding of PHP process signal processing in one article

A thorough understanding of PHP process signal processing in one article

Apr 01, 2023 am 07:30 AM
php process

This article brings you relevant knowledge about PHP, which mainly introduces PHP process signal processing in detail. Friends who are interested can take a look at it together. I hope it will be helpful to everyone.

A thorough understanding of PHP process signal processing in one article

Background

The boss arranged it for me two weeks ago I started a task and wrote a package that listens for signals. Because our company's projects run in containers, every time they go online, they need to repackage the image and then start it. Before repackaging, Dokcer will first send a signal to the container, then wait for a timeout period (default 10s), and then send the SIGKILL signal to terminate the container

Now there is a situation where there is a resident process in the container , the task of this resident process is to continuously consume messages in the queue. Suppose you want to go online now and you need to shut down the container. Docker sends a signal to the resident process running in the container, telling it that I will shut you down in 10 seconds. Suppose now 9 seconds have passed and the resident process has just been taken out of the queue. For a message, the process has been killed before the subsequent logic has been executed within 1 second. At this time, the message is lost, and dirty data may be generated.

The above is the background of this task. It needs to be Determine how to proceed by monitoring the signal. For the above situation, when the resident process receives the shutdown signal sent by Docker, the process can be blocked and sleep until the container is killed. OK, after clarifying the background, let’s introduce the signals in PHP (I will compile an article on how to write this package later, and publish the package to https://packagist.org/ for the use of friends who need it) [Recommended study :PHP video tutorial

1. What are the signals in the Linux operating system

1. Brief introduction to signals

#Signals are notification mechanisms for processes when events occur, sometimes also calledsoftware interrupts . A process can send a signal to another process. For example, when a child process ends, it will send a SIGCHLD (Signal No. 17) to the parent process to notify the parent process, so sometimes signals are also used as an inter-process communication mechanism.

In Linux systems, we usually use kill -9 XXPID to end a process. In fact, the essence of this command is to send SIGKILL (Signal No. 9) to a process. For processes in the foreground, we usually use Ctrl c shortcut key to end the run. The essence of this shortcut key is to send SIGINT (Signal No. 2) to the current process, and the default behavior of the process when receiving this signal is to end the run

2 , Commonly used signals

You can use the kill -l command to view the following signalsThe following introduces several important and commonly used signals:

Signal name Signal value Signal type Signal description
SIGHUP 1 Terminate the process (terminal line hangs up) This signal is issued when the user terminal connection (normal or abnormal, ends), Usually when the terminal's control process ends, each job in the same session is notified. At this time, they are no longer associated with the controlling terminal
SIGQUIT 2 Terminate process (interrupt process) Program termination (interrupt, signal, issued when the user types the INTR character (usually Ctrl-C,
SIGQUIT 3 Create a CORE file to terminate the process, and generate a CORE file The process, and generate a CORE file SIGQUIT is similar to SIGINT, but is preceded by the QUIT character (usually Ctrl-, Control. The process will generate a core file when it exits due to receiving SIGQUIT. In this sense, it is similar to a program error signal
SIGFPE 8 Create CORE file (floating point exception) SIGFPE is issued when a fatal arithmetic operation error occurs. This includes not only floating point operation errors, but also all other arithmetic errors such as overflow and division by 0
SIGKILL 9 Terminate the process (kill the process) SIGKILL is used to end the running of the program immediately. This signal cannot be blocked , handle and ignore
SIGSEGV 11
SIGSEGV attempts to access memory not allocated to itself, or Trying to write data to a memory address that does not have write permission
SIGALRM 14 Terminate the process (timer expires) SIGALRM clock timing signal, which calculates the actual time or clock time. The alarm function uses this signal
SIGTERM 15 to terminate the process (software Termination signal) SIGTERM Program end (terminate, signal, unlike SIGKILL, this signal can be blocked and processed. It is usually used to require the program to exit normally. The shell command kill generates this signal by default
SIGCHLD 17 Ignore signals (notify the parent process when the child process stops or exits) SIGCHLD When the child process ends, the parent The process will receive this signal
SIGVTALRM 26 Terminate the process (virtual timer expires) SIGVTALRM virtual clock Signal. Similar to SIGALRM, but it calculates the CPU time occupied by the process
SIGIO 29 Ignore the signal (can be done on the descriptor I/O) SIGIO file descriptor is ready to start input/output operations

2. Signal processing related functions in PHP

PHP’s pcntl extension and posix The extension provides us with several methods for operating signals (if you want to use these functions, you need to install these extensions first)

The following is a detailed introduction to several methods I used in this task:

declare

The declare structure is used to set the execution instructions for a piece of code. The syntax of declare is similar to other flow control structures

declare (directive)
    statement
Copy after login

The directive part allows you to set the behavior of the declare code segment. Currently, only two instructions are recognized: ticks and encoding. The statement part of the declare code section will be executed - how it is executed and what side effects occur depends on the instructions set in the directive

Ticks

Tick( Clock cycle) is an event that occurs every time the interpreter executes N timeable low-level statements in the declare code segment. The value of N is specified with ticks=N in the directive part of declare. Not all statements can be timed. Usually conditional expression and parameter expression are not timeable. The events that appear in each tick are specified by register_tick_function(). Note that multiple events can appear in each tick. For more detailed information, please view the official documentation: https://www.php.net/manual/zh/control-structures.declare.php

<?php
declare(ticks=1);//每执行一条时,触发register_tick_function()注册的函数
$a=1;//在注册之前,不算
function test(){//定义一个函数
    echo "执行\n";
}
register_tick_function(&#39;test&#39;);//该条注册函数会被当成低级语句被执行
for($i=0;$i<=2;$i++){//for算一条低级语句
    $i=$i;//赋值算一条
}
输出:六个“执行”
Copy after login

pcntl_signal

pcntl_signal, install a signal processor

pcntl_signal ( int $signo , callback $handler [, bool $restart_syscalls = true ] ) : bool
Copy after login

The function pcntl_signal() installs a new signal processor for the signal specified by signo

declare(ticks = 1);
pcntl_signal(SIGINT,function(){
    echo "你按了Ctrl+C".PHP_EOL;
});
while(1){
    sleep(1);//死循环运行低级语句
}
输出:当按Ctrl+C之后,会输出“你按了Ctrl+C”
Copy after login

posix_kill

posix_kill, sends a signal to the process

posix_kill ( int $pid , int $sig ) : bool
Copy after login

The first parameter is the process ID, the second parameter The parameter is the signal you want to send

a.php
<?php
declare(ticks = 1);
echo getmypid();//获取当前进程id
pcntl_signal(SIGINT,function(){
    echo "你给我发了SIGINT信号";
});
while(1){
    sleep(1);
}

b.php
<?php
posix_kill(执行1.php时输出的进程id, SIGINT);
Copy after login

##pcntl_signal_dispatch##pcntl_signal_dispatch, calling the processor waiting for the signal

pcntl_signal_dispatch ( void ) : bool
Copy after login

The function pcntl_signal_dispatch() calls each waiting signal through the processor installed by pcntl_signal()

<?php
echo "安装信号处理器...\n";
pcntl_signal(SIGHUP,  function($signo) {
     echo "信号处理器被调用\n";
});
echo "为自己生成SIGHUP信号...\n";
posix_kill(posix_getpid(), SIGHUP);
echo "分发...\n";
pcntl_signal_dispatch();
echo "完成\n";
?>

输出:
安装信号处理器...
为自己生成SIGHUP信号...
分发...
信号处理器被调用
完成
Copy after login

##pcntl_async_signals()Asynchronous signal processing is used to enable asynchronous signal processing without ticks (which will bring a lot of additional overhead). (PHP>=7.1)
<?php
pcntl_async_signals(true); // turn on async signals

pcntl_signal(SIGHUP,  function($sig) {
    echo "SIGHUP\n";
});

posix_kill(posix_getpid(), SIGHUP);

输出:
SIGHUP
Copy after login

3. The way to handle semaphores in PHPWe know what we know before You can monitor signals by combining declare(ticks=1) and pcntl_signal. That is, every low-level PHP statement will check whether there are unprocessed signals in the current process. This is actually very performance-consuming.

The implementation principle of pcntl_signal is to first add the signal to a queue after triggering the signal. Then continuously check whether there is a signal in PHP's ticks callback function. If there is a signal, execute the callback function specified in PHP. If not, jump out of the function.

PHP_MINIT_FUNCTION(pcntl)
{
 php_register_signal_constants(INIT_FUNC_ARGS_PASSTHRU);
 php_pcntl_register_errno_constants(INIT_FUNC_ARGS_PASSTHRU);
 php_add_tick_function(pcntl_signal_dispatch TSRMLS_CC);

 return SUCCESS;
}
Copy after login

After PHP5.3, there is the pcntl_signal_dispatch function. At this time, declare is no longer needed. You only need to add the function in the loop to call the signal and pass:

<?php
echo getmypid();//获取当前进程id
pcntl_signal(SIGUSR1,function(){
    echo "触发信号用户自定义信号1";
});
while(1){
    pcntl_signal_dispatch();
    sleep(1);//死循环运行低级语句
}
Copy after login

Everyone knows that PHP's ticks=1 means that this function will be called back every time a line of PHP code is executed. In fact, no signal is generated most of the time, but the ticks function is always executed. If a server program receives 1,000 requests in 1 second, on average each request will execute 1,000 lines of PHP code. Then PHP's pcntl_signal brings an additional 1000 * 1000, which is 1 million empty function calls. This will waste a lot of CPU resources. A better approach is to remove ticks and instead use pcntl_signal_dispatch to handle the signal yourself in the code loop. Implementation of pcntl_signal_dispatch function:

void pcntl_signal_dispatch()
{
 //.... 这里略去一部分代码,queue即是信号队列
 while (queue) {
  if ((handle = zend_hash_index_find(&PCNTL_G(php_signal_table), queue->signo)) != NULL) {
   ZVAL_NULL(&retval);
   ZVAL_LONG(&param, queue->signo);

   /* Call php signal handler - Note that we do not report errors, and we ignore the return value */
   /* FIXME: this is probably broken when multiple signals are handled in this while loop (retval) */
   call_user_function(EG(function_table), NULL, handle, &retval, 1, &param TSRMLS_CC);
   zval_ptr_dtor(&param);
   zval_ptr_dtor(&retval);
  }
  next = queue->next;
  queue->next = PCNTL_G(spares);
  PCNTL_G(spares) = queue;
  queue = next;
 }
}
Copy after login

But the above kind of thing also has a disgusting part, that is, it has to be placed in an infinite loop. After PHP7.1, a function that completes asynchronous signal reception and processing came out: pcntl_async_signals

<?php
//a.php
echo getmypid();
pcntl_async_signals(true);//开启异步监听信号
pcntl_signal(SIGUSR1,function(){
    echo "触发信号";
    posix_kill(getmypid(),SIGSTOP);
});
posix_kill(getmypid(),SIGSTOP);//给进程发送暂停信号

//b.php
posix_kill(文件1进程, SIGCONT);//给进程发送继续信号
posix_kill(文件1进程, SIGUSR1);//给进程发送user1信号
Copy after login

With the pcntl_async_signals method, there is no need to write an infinite loop.

监听信号的包:

https://github.com/Rain-Life/monitorSignal
Copy after login

The above is the detailed content of A thorough understanding of PHP process signal processing in one article. For more information, please follow other related articles on the PHP Chinese website!

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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 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.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 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: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

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