共計(jì) 816 個(gè)字符,預(yù)計(jì)需要花費(fèi) 3 分鐘才能閱讀完成。
在 PHP 中,可以使用 exec()
函數(shù)或 shell_exec()
函數(shù)執(zhí)行 shell 腳本。但是這些函數(shù)默認(rèn)是同步執(zhí)行的,如果要實(shí)現(xiàn)異步執(zhí)行,可以使用以下方法:
- 使用
exec()
函數(shù)結(jié)合&
符號(hào):通過在 shell 腳本的末尾添加&
符號(hào),可以將腳本放入后臺(tái)執(zhí)行,實(shí)現(xiàn)異步執(zhí)行。示例代碼如下:
exec('sh script.sh > /dev/null 2>&1 &');
- 使用
proc_open()
函數(shù):proc_open()
函數(shù)可以打開一個(gè)進(jìn)程,并返回一個(gè)資源??梢允褂迷撡Y源進(jìn)行進(jìn)程的控制和通信。通過使用proc_open()
函數(shù),可以實(shí)現(xiàn)異步執(zhí)行 shell 腳本。示例代碼如下:
$descriptorspec = array(0 => array("pipe", "r"), // 標(biāo)準(zhǔn)輸入
1 => array("pipe", "w"), // 標(biāo)準(zhǔn)輸出
2 => array("pipe", "w") // 標(biāo)準(zhǔn)錯(cuò)誤輸出
);
$process = proc_open('sh script.sh', $descriptorspec, $pipes);
if (is_resource($process)) {// 非阻塞讀取輸出
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
// 關(guān)閉標(biāo)準(zhǔn)輸入
fclose($pipes[0]);
// 讀取標(biāo)準(zhǔn)輸出和標(biāo)準(zhǔn)錯(cuò)誤輸出
$output = stream_get_contents($pipes[1]);
$error = stream_get_contents($pipes[2]);
// 關(guān)閉標(biāo)準(zhǔn)輸出和標(biāo)準(zhǔn)錯(cuò)誤輸出
fclose($pipes[1]);
fclose($pipes[2]);
// 關(guān)閉進(jìn)程
proc_close($process);
}
這些方法都可以實(shí)現(xiàn)異步執(zhí)行 shell 腳本,具體使用哪種方法取決于你的需求和環(huán)境。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完