How to asynchronously execute a shell script in PHP?
In PHP, the exec() function can be used to execute shell scripts. However, exec() is synchronous, meaning that the PHP script will wait until the shell script has finished executing. To achieve asynchronous execution of shell scripts, the following method can be used:
- execute()
- Can you please put that in your own words?
exec("your_script.sh > /dev/null 2>&1 &");
Redirect the output of the script to /dev/null 2>&1 here, with the “&” symbol indicating that the script will be executed in the background.
- Execute a shell command
- The command “nohup”
shell_exec("nohup your_script.sh > /dev/null 2>&1 &");
The nohup command is used to ignore the HUP (hang up) signal and run a script in the background.
- a function called proc_open()
- Make the data stream blocking or non-blocking.
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a pipe that the child will write to
);
$process = proc_open("your_script.sh", $descriptorspec, $pipes);
// 设置为非阻塞模式
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
// 关闭不需要的管道
fclose($pipes[0]);
// 获取脚本的输出
$output = stream_get_contents($pipes[1]);
$error = stream_get_contents($pipes[2]);
// 关闭管道和进程
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
Here are several methods in PHP to implement asynchronous execution of shell scripts. Choose the appropriate method based on your actual needs.