In Linux, you can add the "&" symbol at the end of the command to hold a script in the background for execution. Sometimes this is not enough. You need to use the nohup command, about nohup,
Anyone who has played Linux should know that if you want to run a program in the background, you only need to add an & symbol at the end of the command. However, this method is not very safe. Some programs will stop when you log out of the terminal. So how can we make a program always run in the background. The answer is to use the nohub command in the format:
Nohup command for executing the program &
If the program has output, it will try to write the output
In the nohup. out file in the current folder that runs the preceding command, if the write fails, it will write the nohup. out file in the $ HOME directory of the current user.
The operations performed in the CLI environment and Web environment are not the same. First, we need to use nohup and & in the CLI environment, and specify the output. If you do not want to output the result, you can direct the output to/dev/null. Now let's do a test. Suppose there are main. php, sub1.php, and sub2.php in a directory. sub1 and sub2 both pause the sleep function for a while. The code is as follows:
The code is as follows: |
Copy code |
// Main. php <? Php $ Cmd = 'nohup php./sub. php>./tmp. log &'; Exec ($ cmd ); $ Cmd = 'nohup php./sub1.php>/dev/null &'; Exec ($ cmd ); ?> // Sub1.php sub2.php <? Php Sleep (100000 ); ?> |
In the above file, main. php is used as the main script. Execute php main. php in the command line. You can see that the main. php script is executed soon and exits. When you use the ps aux | grep sub Command to search for a process, you can see the two sub-scripts in the background, indicating that the sub-scripts are successfully suspended.
In the Web environment, the execution of php scripts is handled by cgi processes enabled by the Web server. As long as the script does not exit, it will always occupy the cgi process, when all the started cgi processes are occupied, new requests cannot be processed. Therefore, the asynchronous method can be used for scripts that may take a long time. The method for starting a script is similar to CLI. You must use & and specify the output (to be directed to/dev/null), but not use nohup. For example:
The code is as follows: |
Copy code |
<? Php $ Cmd = 'php PATH_TO_SUB1/sub1.php>/dev/null &'; Exec ($ cmd ); $ Cmd = 'php PATH_TO_SUB1/sub2.php>/dev/null &'; Exec ($ cmd ); ?>
|
When you access the script file in the browser, you can see that the response is complete in the browser, and you can also view the sub1 and sub2 scripts in the background using the ps command.
Note: In the above example, if the php command is not in the PATH, you must specify the complete PATH of the command. We recommend that you use the full path, especially on the Web.