This article mainly introduces the PHP asynchronous execution script Introduction, has a certain reference value, now share to everyone, the need for friends can refer to
The asynchronous execution here is to have the PHP script suspend a script in the background that performs a specific action, and after the main script exits, the pending script can continue to execute. For example, some time-consuming operations or operations that can be performed in parallel can take the form of PHP asynchronous execution. Communication between the main script and the sub-script can take the form of an external file or memcached. The principle is to execute an external command via exec or system. Note: This article describes the Linux environment.
Under Linux to let a script hanging in the background can be executed at the end of the command with a "&" symbol, sometimes this is not enough, you need to use the Nohup command, about Nohup, you can refer to http://www.netingcn.com/linux-nohup.html.
The CLI environment and the Web environment do not have the same actions. First of all, the CLI environment, the need to use the nohup and &, but also the specified output, if you do not want to output the results, you can direct the output to/dev/null. Now do a test, assuming that there are main.php, sub1.php, and sub2.php in a directory, where Sub1 and sub2 content let the sleep function pause for a while. The code is as follows:
In the above file, main.php is the main script, executing PHP main.php on the command line, you can see that the main.php script executes and exits shortly. When using PS aux | The grep sub command search process should be able to see the above two sub-scripts in the background, stating that the child script was successfully suspended.
In a Web environment, executing PHP scripts is handled by the Web server's CGI process, and as long as the script does not exit, it will always occupy the CGI process, and when all the CGI processes that are started are consumed, new requests cannot be processed. So for scripts that can be time-consuming, you can use asynchronous methods. You start a sub-script in the same way as the CLI, you must use & and specify the output (only directed to/dev/null), but you cannot use Nohup. For example:
When the script file is accessed in the browser, you can see that the response in the browser is complete, and you can see the sub1 and SUB2 scripts using the PS command to view the background.
Note In the above example, if the PHP command is not in path, you need to specify the full path to the command. It is recommended to use the full path, especially under the web.
The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!