php-pcntlHow to use pcntl_signal in PHP?
PCNTL stands for Process Control, and is a PHP extension that allows you to execute Unix-like signals in your PHP scripts.
Using PCNTL_Signal allows you to catch signals sent to your script and handle them accordingly.
Example
<?php
// Declare the signal handler
function sig_handler($signo)
{
switch ($signo) {
case SIGTERM:
// handle shutdown tasks
exit;
break;
case SIGHUP:
// handle restart tasks
break;
case SIGUSR1:
echo "Caught SIGUSR1\n";
break;
default:
// handle all other signals
}
}
// Setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");
pcntl_signal(SIGUSR1, "sig_handler");
// Do some work
while (true) {
sleep(1);
echo "Working...\n";
}
?>
Output example
Working...
Working...
Caught SIGUSR1
Working...
Code explanation
-
Declare the signal handler: This is a function that will be called when a signal is received. It takes one argument, the signal number, and should contain a switch statement to handle different signals.
-
Setup signal handlers: This is where you specify which signals you want to handle and which function should be called when they are received.
-
Do some work: This is the main body of your script. It should contain the code that you want to execute.
Helpful links
More of Php Pcntl
- How to use PCNTL alarm in PHP?
- How to use pcntl_wifexited in PHP?
- How to use pcntl_waitpid in PHP?
- How to get the process ID with PHP PCNTL?
- How to prevent zombie processes with the PCNTL_FORK function in PHP?
- How to use pcntl_wexitstatus in PHP?
- How to use pcntl_wait in PHP?
- How to install PCNTL for PHP in Debian?
- How to check if PCNTL is enabled in PHP?
See more codes...