Search code examples
phpjsonexternal-process

Control an external process with PHP


I have a web page where I show the status of some processes (in a table, one row for each process). The user have the options to start the process or to force it to stop.

When the user click to start a process, a JSON object is send to a web service that (using PHP) start the process, like below:

<?php
    $params = json_decode($_POST["object"]);
    /** Do something with the params **/

    // Start a external process in background (I'm using 'ls' as an example)
    exec("ls &", $output);

    /** Finish the script **/

The problem is: this external process can take several minutes to complete. So, I would like to give the option to stop it. What I want is: when the user click the "stop" button, it will send a JSON object to a web service (in the same server, of course) to stop the process.

How do I keep track of the external process? How do I force it to stop if needed? And how do I make the user to have the control over it? Is it possible in PHP?


Solution

  • When you start your process with & the process is running in background and you get the process id as return. So you could save that pid in a session for example and kill that process if needed.

    For this you can use the posix_kill command. Perhaps you can then trigger your event and send another request to stop that process.