gpt4 book ai didi

php - 我如何捕获 KILL 或 HUP 或用户中止信号?

转载 作者:可可西里 更新时间:2023-10-31 23:03:11 26 4
gpt4 key购买 nike

我有一个脚本在我的 Linux 服务器的后台运行,我想捕获诸如重启之类的信号或任何会终止该脚本的信号,而不是在实际退出之前保存任何重要信息。

我认为我需要捕获的大部分内容是 SIGINT、SIGTERM、SIGHUP、SIGKILL。

如何捕捉这些信号并让它执行退出函数,否则继续执行它正在做的事情?

伪perl代码:

#!/usr/bin/perl

use stricts;
use warnings;

while (true)
{
#my happy code is running
#my happy code will sleep for a few until its breath is back to keep running.
}

#ops I have detected an evil force trying to kill me
#let's call the safe exit.
sub safe_exit()
{
# save stuff
exit(1);
}

伪PHP代码:

<?php

while (1)
{
#my happy code is running
#my happy code will sleep for a few until its breath is back to keep running.
}

#ops I have detected an evil force trying to kill me
#let's call the safe exit.

function safe_exit()
{
# save stuff
exit(1);
}
?>

最佳答案

PHP 使用 pcntl_signal注册一个信号处理程序,所以像这样:

declare(ticks = 1);

function sig_handler($sig) {
switch($sig) {
case SIGINT:
# one branch for signal...
}
}

pcntl_signal(SIGINT, "sig_handler");
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP, "sig_handler");
# Nothing for SIGKILL as it won't work and trying to will give you a warning.

关于php - 我如何捕获 KILL 或 HUP 或用户中止信号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7864349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com