How do I get the PHP-FPM process to terminate when

2019-06-22 18:02发布

问题:

I know Nginx has nothing to do with the PHP-FPM process, but I would much prefer if the PHP-FPM process died if a user aborts so it doesn't continue doing needless things or wasting resources. For PHP-FPM/Nginx the trigger_error will happen regardless of user abort:

<?php

sleep(30);
trigger_error('Still happened?');

?>

How can I do user aborts for PHP-FPM? (if possible)

回答1:

This is not implemented by php-fpm, more info here.

Setting ignore_user_abort(FALSE) only works when PHP sends data over the socket, not when it is busy calculating a response.

Ideally, it should be implemented in php-fpm, but I don't think it will be very easy, given that PHP is mostly single threaded.

In emergency situations, you could kill all php-fpm processes with a broken connection. Assuming you have php-fpm listening on localhost:9000, this would work:

netstat -ntp | grep 127.0.0.1:9000 | grep php-fpm | grep CLOSE_WAIT |\
awk ' { print $7; } ' | cut -d/ -f1 | while read pid; do
    echo "Killing php-fpm/$pid because client has closed connection"
    kill $pid
done


回答2:

You can decide whether or not you want a client disconnect to cause your script to be aborted.

According to PHP Manual : Connection Handling

To set this behavior use ignore_user_abort

ignore_user_abort(FALSE); will abort running of PHP script after client disconnect.

ignore_user_abort(TRUE); will ignore the client disconnect and continues to run the script.

In the second case, you may also want to use set_time_limit based on your needs to give your script enough time to accomplish the task.

This setting has been tested in a PHP-FPM/nginx environment successfully.



回答3:

You have to check your nginx config, before trying to set the behaviour on the PHP script.

The settings linked by @YAAK don't always work with nginx. In my actual case it is not possible to stop the script, regardless what you do on PHP side.

Playing on the nginx fastcgi parameter fastcgi_ignore_client_abort (default set to off) could help.

Additionally, a manual solution (just for development environment) is to execute (on Linux): sudo service php5-fpm restart, so that the script will be blocked.