


A thorough understanding of PHP process signal processing in one article
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.
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
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('test');//该条注册函数会被当成低级语句被执行 for($i=0;$i<=2;$i++){//for算一条低级语句 $i=$i;//赋值算一条 } 输出:六个“执行”
pcntl_signal
pcntl_signal, install a signal processor
pcntl_signal ( int $signo , callback $handler [, bool $restart_syscalls = true ] ) : bool
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”
posix_kill
posix_kill, sends a signal to the process
posix_kill ( int $pid , int $sig ) : bool
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);
##pcntl_signal_dispatch##pcntl_signal_dispatch, calling the processor waiting for the signal
pcntl_signal_dispatch ( void ) : bool
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信号... 分发... 信号处理器被调用 完成
##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
<?php pcntl_async_signals(true); // turn on async signals pcntl_signal(SIGHUP, function($sig) { echo "SIGHUP\n"; }); posix_kill(posix_getpid(), SIGHUP); 输出: SIGHUP
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; }
<?php echo getmypid();//获取当前进程id pcntl_signal(SIGUSR1,function(){ echo "触发信号用户自定义信号1"; }); while(1){ pcntl_signal_dispatch(); sleep(1);//死循环运行低级语句 }
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(¶m, 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, ¶m TSRMLS_CC); zval_ptr_dtor(¶m); zval_ptr_dtor(&retval); } next = queue->next; queue->next = PCNTL_G(spares); PCNTL_G(spares) = queue; queue = next; } }
<?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信号
监听信号的包:
https://github.com/Rain-Life/monitorSignal
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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,

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

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 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 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 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 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

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.
