在 PHP 的 pcntl_fork() 函數中處理異常情況需要謹慎對待
$pid = pcntl_fork();
if ($pid == -1) {
die("Could not fork");
} else if ($pid) { // Parent process
// Parent process code
} else { // Child process
try {
// Child process code that may throw exceptions
} catch (Exception $e) {
// Handle exception
echo "Caught exception: " . $e->getMessage();
}
}
pcntl_signal()
函數注冊信號處理器。這允許您在子進程中捕獲特定的信號(例如,SIGTERM),并在信號到達時執行自定義操作。function handleSignal($signo)
{
switch ($signo) {
case SIGTERM:
// Handle termination signal
echo "Termination signal received\n";
exit;
default:
// Handle other signals
echo "Unknown signal received: $signo\n";
}
}
$pid = pcntl_fork();
if ($pid == -1) {
die("Could not fork");
} else if ($pid) { // Parent process
// Parent process code
} else { // Child process
pcntl_signal(SIGTERM, 'handleSignal');
while (true) {
// Child process code
pcntl_signal_dispatch();
usleep(100);
}
}
$pid = pcntl_fork();
if ($pid == -1) {
die("Could not fork");
} else if ($pid) { // Parent process
pcntl_waitpid($pid, $status);
if (pcntl_wifexited($status)) {
$exitStatus = pcntl_wexitstatus($status);
if ($exitStatus != 0) {
// Child process exited with an error
echo "Child process exited with status: $exitStatus\n";
}
} else {
// Child process terminated due to an uncaught exception or signal
echo "Child process terminated unexpectedly\n";
}
} else { // Child process
// Child process code
}
通過結合這些方法,你可以更好地處理 PHP Fork 中的異常情況。