所以我已經開發了一段時間的 PHP,并且一直在嘗試解決為什么帶有標準 IO 重定向的 exec 仍然掛起主執行緒。
exec(escapeshellcmd("php ".getcwd()."/orderProcessing.php" . " " . $Prepared . " " . escapeshellarg(35). "> /dev/null 2>&1 &"));
提供的代碼是我一直在試用的,我似乎無法讓它在其他腳本完成之前不掛起。我這樣做的原因是在這種特殊情況下,處理訂單最多可能需要 30 秒,我不希望前端的用戶等待。
我只能使用 php-fpm 生成子行程嗎?
有什么我配置錯誤的嗎?
我只是誤解了子行程的作業方式嗎?
設定是:帶有 Apache HTTPD 和 PHP 8.1.11 的 Centos 7
任何幫助表示贊賞!
uj5u.com熱心網友回復:
是的,這在 PHP 中是可能的。使用 proc_open() 函式,您可以發送命令而無需等待另一個行程。使用句柄打開的流,您可以捕獲行程狀態并始終檢查它。例如:
$max = 5;
$streams = [];
$command = 'php ' . __DIR__ . '/../../process runSomeProcessCommand';
while (true) {
echo 'Working :' . count($streams) . "\n";
for ($i = 0; $i < $max; $i ) {
if (!isset($streams[$i])) {
$descriptor = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w']
];
echo "proc opened $i \n";
$streams[$i]['proc'] = proc_open($command . ":$i", $descriptor, $pipes);
$streams[$i]['pipes'] = $pipes;
$streams[$i]['ttl'] = time();
usleep(200000);
} else {
$info = proc_get_status($streams[$i]['proc']);
if ($info['running'] === false) {
echo "Finished $i . TTL: (" . (time() - $streams[$i]['ttl']) . " sec.).Response: " . stream_get_contents($streams[$i]['pipes'][1]) . " \n";
fclose($streams[$i]['pipes'][1]);
if ($error = stream_get_contents($streams[$i]['pipes'][2])) {
echo "Error for $i. Error: $error " . PHP_EOL;
fclose($streams[$i]['pipes'][2]);
}
proc_close($streams[$i]['proc']);
unset($streams[$i]);
} else {
echo "Running process (PID {$info['pid']}) - $i: \n";
}
# $return_value = proc_close($streams[$i]);
}
}
sleep(3);
}
同一時間有 5 個執行緒彼此不等待。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/529413.html
標籤:php多线程
上一篇:執行緒不并發執行
