Search code examples
phpshell-execterminate

PHP shell_exec - how to terminate the process if the connection is closed?


I have a working php script using shell_exec to execute an external program that take about 30 seconds to complete. Problem is that if an user close the browser or the connection is closed for some reason the program executed with shell_exec continue to run for nothing, since it's output can't be sent to the user anymore.

Is there a way to kill this process as soon as the connection is closed?

Thank you for your help.


Solution

  • Finally I've solved it!

    I've used the PHP function connection_aborted() to check if the client is disconnected. https://www.php.net/manual/en/function.connection-aborted.php

    The algorithm is the following (pseudocode)

    shell_exec("script");//script is a shell script that launch the program in another thread thus this return immediately
    $task_completed=false;
    while(!$task_completed){
        if(connection_aborted()==1){
            kill_the_process();//this will kill the running process launched by script
            die();
        }
        $task_completed=...;//true if the task completed
        sleep(1);
    }