PHP shell_exec wait for script to done? [duplicate

2019-09-28 06:41发布

问题:

This question already has an answer here:

  • PHP shell_exec wait for script to finish? [duplicate] 1 answer

I have a PHP script that queries a database for a list of jobs to be done and fires off other PHP scripts based on what it finds in the database (basically a process queue).

Some of the scripts that the queue runner script executes may take 30 seconds or so to finish running (convert video, resizing images, etc).

The problem is that shell_exec() in the queue runner script calls the processing scripts, but then doesn't wait for them to finish, resulting in the queue not being completed.

Queue runner script:

#!/usr/bin/php
<?php
    // Loop through database and find jobs to be done
    shell_exec("nohup $command > /dev/null 2> /dev/null & echo $! &");
?>

Running the job script directly from the command line works and the PDF is created.

Any ideas on how to fix this? Or a better way to run a process queue?

回答1:

shell_exec is not the cause of your problems. It'll wait and return the output of your command. However, you mustn't start your command in the background and using nohup.

nohup is the command you are calling but as soon as it has started its child process it will exit immediatelly, thus, shell_exec will not wait for that process to be completed. You should also refrain from running the command in the background with &.



回答2:

I'd first suggest not executing code from PHP but use PHP wrappers and libraries whenever possible.

One problem I see is that your processing is synchronous, this means the user will have to wait that the server responds without any clue about what is going on. He may even refresh the page which would increase the load of your server without control, and this is a very serious issue. This would enable a DOS attack.

I suggest AJAX for these long-running task. You can display something to show progress on the webpage and update it (AJAX) when it's done or switch to another page. You can even handle the case of the user quitting the page by catching that event in javascript and killing the process.