Home > Article > Backend Development > 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.
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】
#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
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 |
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:
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, 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, 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 ( 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信号... 分发... 信号处理器被调用 完成
<?php pcntl_async_signals(true); // turn on async signals pcntl_signal(SIGHUP, function($sig) { echo "SIGHUP\n"; }); posix_kill(posix_getpid(), SIGHUP); 输出: SIGHUP
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; }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);//死循环运行低级语句 }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(¶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; } }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信号With the pcntl_async_signals method, there is no need to write an infinite loop.
监听信号的包:
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!