租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

php怎么异步执行shell脚本,php异步执行function

发布时间:2023-12-29 19:19:30

php怎样异步履行shell脚本

在PHP中,可使用exec()函数来履行shell脚本。但是exec()函数是同步的,即在履行完shell脚本之前,PHP脚本会一直等待。如果希望实现异步履行shell脚本,可使用以下方法:

  1. 使用exec()函数结合&符号将脚本放入后台履行,例如:
exec("your_script.sh > /dev/null 2>&1 &");

这里的> /dev/null 2>&1是将脚本的输出重定向到空装备,&符号表示将脚本放入后台履行。

  1. 使用shell_exec()函数结合nohup命令,例如:
shell_exec("nohup your_script.sh > /dev/null 2>&1 &");

nohup命令用于疏忽HUP(挂起)信号,并将脚本放入后台履行。

  1. 使用proc_open()函数来履行shell脚本并获得进程句柄,然后使用stream_set_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);

以上是几种在PHP中实现异步履行shell脚本的方法,根据实际需求选择适合的方法。