Being able to capture signals from our PHP code can be very useful in certain situations, for example when a file is opened to save logs and is never closed, it will grow indefinitely and even if the file is truncated, the file descriptor will still be occupied by our process, preventing the space from being freed. To solve this problem, we can use signals, the code receives the signal, closes the file and reopens it, allowing the OS to free up space.
We compile PHP with the pcntl use flag:
vi /etc/portage/package.use/php
dev-lang/php apache2 berkdb bzip2 cli crypt ctype curl curlwrappers exif fileinfo filter ftp gd gdbm hash iconv imap intl json mysql mysqli nls odbc pdo phar posix readline session simplexml soap sockets sqlite3 ssl sysvipc threads tokenizer unicode xml xmlreader xmlrpc xmlwriter zip zlib threads fpm cgi truetype bcmath ldap pcntl
We program our little gadget:
vi signal.php
<?php
declare(ticks = 1);
echo "Installing signal handler...\n";
pcntl_signal(SIGUSR1, function($signo) {
echo "Signal handler called\n";
});
echo "Done\n";
echo "PID: " . posix_getpid() . "\n";
echo "Waiting signal\n";
while(true){
sleep(1);
}
?>
Let’s test our piece of code:
php signal.php
Installing signal handler...
Done
PID: 29763
Waiting signal
We send the SIGUSR1 signal:
kill -SIGUSR1 PID
The code works as expected by capturing the signal:
Installing signal handler...
Done
PID: 29763
Waiting signal
Signal handler called