断电前执行功能

How do i execute a function when poweroff is triggered?

// need to make sure here that poweroff command is executed successfully before calling senEmail function
$output = exec('poweroff', $output, $return);
if (!$return) {
    // command executed successfully
    // now send email before poweroff completes its process
    sendEmail();
}

sendEmail() is not triggered since shutdown is already processing.

Slightly depending on the system details, poweroff will call shutdown, which is probably a better match to call from your program. shutdown can be instructed to bring the system down after a period.

You could have the mail sent in response to the SIGTERM signal, which the shutdown process will send. There are plenty of resources available on that. There is always the risk that the processes that are needed to send the email are already on their way down.

Better yet you can flip the order of dependency: call shutdown with a reasonable grace period, try to send the email, and if the sending fails, cancel the shutdown.