PHP shell_exec wait for script to done? [duplicate]

给你一囗甜甜゛ 提交于 2019-12-13 23:17:24

问题


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.



来源:https://stackoverflow.com/questions/11524063/php-shell-exec-wait-for-script-to-done

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!