问题
I have a simple PHP script that I want to run from the terminal, and be able to process signal codes. The script creates a TCP server and processes connections. Not sure why, but I can't get signal processing to work:
<?php
declare(ticks = 1);
// Register shutdown command.
pcntl_signal(SIGINT, function ($sig) {
echo 'Exiting with signal: ' . $sig;
global $sock;
global $client;
socket_close($sock);
socket_close($client);
exit(1);
});
$address = '127.0.0.1';
$port = 1234;
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($sock, $address, $port) or die('Could not bind to address.');
socket_listen($sock);
while (TRUE) {
$client = socket_accept($sock);
if ($client) {
$input = socket_read($client, 1024000);
socket_write($client, var_export($input, TRUE));
socket_write($client, 'End of data transmission.');
socket_close($client);
}
usleep(100);
}
CTRL+C does not kill the application or hit the function.
If I remove the pcntl_signal
functions, CTRL+C kills the program as expected.
Based on the research I've done, this setup should work. I've tried it in PHP 5.5 and 5.6... Cannot get to work as intended.
回答1:
Problem
The problem is that you are using socket_read()
which performs blocking IO. PHP isn't able to process signals if it hangs in a blocking IO operation.
Solution
Use non blocking IO to read data from the socket. You can use the function socket_select()
with a timeout in a loop to make sure a read wouldn't block.
来源:https://stackoverflow.com/questions/26934216/pcntl-signal-function-not-being-hit-and-ctrlc-doesnt-work-when-using-sockets