What is happening?
When you send the Ctrl + C
command, PHP
tries to finish the current action before exiting.
Why does my (OP's) code not exit?
SEE FINAL THOUGHTS AT THE END FOR A MORE DETAILED EXPLANATION
Your code does not exit because cURL
doesn't finish, so PHP
cannot exit until it finishes the current action.
The website you've chosen for this exercise never loads.
How to fix
To fix, replace the URL with something that does load, like https://google.com, for instance
Proof
I wrote my own code sample to show me exactly when/where PHP
decides to exit:
<?php
declare(ticks=1);
$t = 1;
$shutdownHandler = function () {
exit("EXITING NOW\n");
};
pcntl_signal(SIGINT, $shutdownHandler);
while (true) {
print "$t\n";
$t++;
}
When running this in the terminal, you get a much clearer idea of how PHP is operating:
In the image above, you can see that when I issue the SIGINT command via Ctrl + C
(shown by the arrow), it finishes up the action it is doing, then exits.
This means that if my fix is correct, all it should take to kill curl in OP's code, is a simple URL
change:
<?php
declare(ticks=1);
$t = 1;
$shutdownHandler = function () {
exit("\nEXITING\n");
};
pcntl_signal(SIGINT, $shutdownHandler);
while (true) {
echo "CURL$t\n";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://google.com');
curl_exec($ch);
curl_close($ch);
}
And then running:
Viola! As expected, the script terminated after the current process was finished, like its supposed to.
Final thoughts
The site you're attempting to curl is effectively sending your code on a trip that has no end. The only actions capable of stopping the process are CTRL + X
, the max execution time setting, or the CURLOPT_TIMEOUT
cURL option. The reason CTRL+C
works when you take OUT pcntl_signal(SIGINT, $shutdownHandler);
is because PHP no longer has the burden of graceful shutdown by an internal function. Since PHP isn't concurrent, when you do have the handler in, it has to wait its turn before it is executed - which it will never get because the cURL
task will never finish, thus leaving you with the never-ending results.
I hope this helps!
$shutdownHandler = function () use(&$ch){ echo 'Exiting'; curl_close($ch); echo "curl closed.\n"; exit(); };
? – Counterforcesleep(30)
like :while ($testing) { echo "Sleeeeeping..." . PHP_EOL; sleep(10); echo "Awake!" . PHP_EOL; }
doing a ctrl+C causes thesleep
to halt and "Awake!" to get printed earlier than expected, but it returns right back to the loop. Even if I have$testing = false;
in my signal handler. – Proudhonunable to call the SIGINT handler during curl_exec()
), someone should take it to bugs.php.net – Counterforce7.0.X
. See if this gist is a acceptable solution to you? gist.github.com/tarunlalwani/6b4f2b81f20c781234899e62f22b0436, if it is then only I will post an answer – Gonion